- 定义结构体及声明变量
struct Student {
int id;
char name[20];
float score;
};
struct Student stu1;
- 常见语法错误及注意事项
- 结构体定义结尾分号遗漏:在结构体定义的最后,右花括号
}
后必须紧跟一个分号 ;
,如遗漏会导致语法错误。例如:
// 错误示范,遗漏结尾分号
struct Student {
int id;
char name[20];
float score;
}
// 此时编译会报错
- 结构体变量声明格式错误:声明结构体变量时,需要使用正确的结构体类型名。例如:
// 错误示范,未使用struct关键字
Student stu2;
// 正确示范
struct Student stu2;
- 初始化语法错误:在声明变量并初始化时,要按照结构体成员顺序提供对应类型的值。例如:
// 错误示范,类型不匹配
struct Student stu3 = {1, 123, 3.5};
// 正确示范
struct Student stu3 = {1, "Tom", 3.5};
- 成员访问语法错误:在访问结构体变量的成员时,要使用正确的点运算符
.
。例如:
struct Student stu4;
// 错误示范,使用错误的运算符
stu4->id = 2;
// 正确示范,结构体变量使用点运算符
stu4.id = 2;
- 结构体嵌套时的注意事项:如果结构体中包含其他结构体类型的成员,在定义内部结构体时要确保其已经定义。例如:
struct Address {
char city[20];
};
struct Person {
int age;
struct Address addr; // 这里Address结构体需提前定义
};