2.结构体
结构体定义:使用struct关键字来定义结构体,如:
struct student {
int id;
char name[20];
float score;
};
结构体变量定义与初始化:使用结构体定义来定义一个结构体变量,并使用"."来访问结构体中的成员变量,如:
struct student std1;
std1.id = 1;
strcpy(std1.name, "Tom");
std1.score = 89.5;
结构体作为函数参数:结构体可以作为参数传递给函数,如:
void printInfo(struct student std) {
printf("ID: %d\nName: %s\nScore: %f\n", std.id, std.name, std.score);
}
结构体指针:使用结构体指针可以方便地访问结构体。使用箭头运算符 -> 来访问结构体成员,如:
struct student *p_std;
p_std = &std1;
p_std->id = 2;
strcpy(p_std->name, "Jerry");
p_std->score = 91.2;
结构体嵌套:结构体中可以包含其他结构体类型的成员变量,如:
struct class {
int class_id;
struct student std_array[5]; // 一个班级包含5个学生
};
总之,结构体可以方便地组织和管理多个相关的数据项,是C语言中非常重要和常用的数据类型之一。
struct student {
int id;
char name[20];
float score;
};
结构体变量定义与初始化:使用结构体定义来定义一个结构体变量,并使用"."来访问结构体中的成员变量,如:
struct student std1;
std1.id = 1;
strcpy(std1.name, "Tom");
std1.score = 89.5;
结构体作为函数参数:结构体可以作为参数传递给函数,如:
void printInfo(struct student std) {
printf("ID: %d\nName: %s\nScore: %f\n", std.id, std.name, std.score);
}
结构体指针:使用结构体指针可以方便地访问结构体。使用箭头运算符 -> 来访问结构体成员,如:
struct student *p_std;
p_std = &std1;
p_std->id = 2;
strcpy(p_std->name, "Jerry");
p_std->score = 91.2;
结构体嵌套:结构体中可以包含其他结构体类型的成员变量,如:
struct class {
int class_id;
struct student std_array[5]; // 一个班级包含5个学生
};
总之,结构体可以方便地组织和管理多个相关的数据项,是C语言中非常重要和常用的数据类型之一。
全部评论
相关推荐
点赞 评论 收藏
分享
点赞 评论 收藏
分享
05-19 19:57
蚌埠学院 Python 点赞 评论 收藏
分享