🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
结构体是一种自定义的数据类型,所以结构体类型的声明最好和结构体变量的定义区分开。 ~~~ #include <stdio.h> typedef struct student //结构体类型的申明与定义分开。这里是类型 声明;一般放在.h文件中 { int age; /*年龄*/ float score; /*分数*/ char sex; /*性别*/ }Student; int main () { Student a={ 20,79,'f'}; //结构体定义的第一种方式 //第二种方式 Student *pstu=malloc(sizeof(Student)); pstu->age=20; pstu->score=79; pstu->sex='f'; printf("年龄:%d 分数:%.2f 性别:%c\n", a.age, a.score, a.sex ); return 0; } ~~~ 结构体变量定义的两种方式 //结构体定义的第一种方式,通常的变量定义形式,但是一般情况下我们**传递结构体变量都是传地址以减少赋值内存内容的开销**,所以一般情况下还有一个语句:Student *pa=&a; Student a={ 20,79,’f’}; Student *pa=&a; 我们干嘛不直接定义一个指向结构体变量的指针呢?所以体现了第二种方法的便利性。 //第二种方式 Student *pstu=malloc(sizeof(Student)); pstu->age=20; pstu->score=79; pstu->sex=’f’; 传递参数的时候直接把pstu传过去就over了。