c语言

c语言怎么定义结构体变量

小亿
95
2023-11-23 17:51:34
栏目: 编程语言

在C语言中,可以使用struct关键字定义一个结构体,并通过声明变量来创建结构体变量。

定义结构体的语法如下:

struct 结构体名称 {
    数据类型 成员1;
    数据类型 成员2;
    // ...
};

其中,结构体名称是自定义的,可以根据需要命名,成员可以包含任意类型的数据。

例如,定义一个表示学生信息的结构体:

struct Student {
    int id;
    char name[20];
    int age;
};

然后,可以通过声明变量来创建结构体变量:

struct Student stu1; // 创建一个名为stu1的结构体变量
struct Student stu2; // 创建一个名为stu2的结构体变量

也可以在定义结构体的同时声明变量:

struct Student {
    int id;
    char name[20];
    int age;
} stu1, stu2; // 同时创建名为stu1和stu2的结构体变量

接下来,可以通过结构体变量名和成员运算符.来访问结构体的成员:

stu1.id = 1; // 对stu1的id成员赋值为1
strcpy(stu1.name, "Alice"); // 对stu1的name成员赋值为"Alice"
stu1.age = 20; // 对stu1的age成员赋值为20

printf("学生信息:\n");
printf("学号:%d\n", stu1.id);
printf("姓名:%s\n", stu1.name);
printf("年龄:%d\n", stu1.age);

这样就可以定义和使用结构体变量了。

0
看了该问题的人还看了