结构体---C语言
在C语言中,结构体(struct) 是一种用户自定义的数据类型,它允许你将多个不同类型的数据组合在一起,形成一个整体。
某些情况下,需要用多个变量描述同一个个体,如果不用结构体,你需要定义多个独立的变量,管理起来非常零散。
// 方式一:定义类型(常用) struct Student { int id; char name[50]; float score; }; // 方式二:定义类型的同时声明变量 struct { int id; char name[50]; } stu1, stu2; // 方式三:使用typedef起别名 typedef struct { int id; char name[50]; float score; } Student; // 现在Student就相当于数据类型,省去"struct"(可读性略差,需要多次声明时方便)结构体里面也可以放结构体(结构体就像是自己创建的一种数据类型)先创建小的结构体,然后可以直接放入大的结构体中
结构体中的值的引用方法
#include <stdio.h> typedef struct { int id; char name[50]; float score; } Student; int main() { // 直接初始化 Student stu1 = {1, "linke", 99}; printf("%d ", stu1.id); // 输出1 printf("%s ", stu1.name); // 输出linke printf("%.2f\n", stu1.score); // 输出99.00 // ========== 指针引用值的多种方式 ========== // 方式1:定义指针指向结构体变量 Student *p = &stu1; printf("\n--- 指针引用方式 ---\n"); printf("通过指针访问: %d %s %.2f\n", (*p).id, (*p).name, (*p).score); // 方式2:使用箭头运算符(推荐) printf("通过箭头访问: %d %s %.2f\n", p->id, p->name, p->score); // 方式3:修改指针指向的值 p->score = 100; printf("修改后的成绩: %.2f\n", stu1.score); return 0; }