目录
1.结构体的定义与使用
2.结构体数组
3.结构体指针
4.结构体然后计算大小
5.typedef关键字
6.结构体常见问题
1.结构体的定义与使用
结构体跟我们之前接触的数组的概念很相似,数组是类型相同的一组变量的集合,而结构体类型不同的一组变量的集合。这样就会使数据更多,类型更丰富,数据量更大。
结构体在定义的时候我们不关心这个结构体里面变量的值,它就类似于模板一样,至于变量的大小或内容我们再编程的时候会给它们补充完整,哪怕定义的变量没有用到也是可以的。
如何定义结构体
在给结构体中的赋值的时候,可以类比我们平时给普通变量赋值的情况。
struct student //struct关键字+结构体名字
{
int score;
char name[128];
}; //记得有分号
int main()
{
//类型 变量名 初始值
int a = 10;
struct student stu = {98,"jhsad"};
//struct student可以看作是我们自定义的一种类型
return 0;
}
如何访问结构体
上面我们已经定义好了一个结构体,现在我们把结构体里面的值拿出来访问。同样类比普通变量的访问方式。
#include#include struct student { int score; char name[128]; }; int main() { int a = 10; //第一种访问方式 struct student stu = {98,"jhsad"}; printf("a=%dn",a); //普通变量的访问方式 printf("score=%dn",stu.score);//访问结构体用.运算符 printf("name=%sn",stu.name); //第二种访问方式 struct student text; text.score = 20; strcpy(text.name,"李四"); printf("score=%dn",text.score); printf("name=%sn",text.name); return 0; }
2.结构体数组
结构体数组的定义方式跟上面都一样的,还是通过类比普通数组的定义方式。
#includestruct student { int sorce; char *name; }; int main() { // 类型 变量 大小 int a [3]; struct student stu[3]; return 0; }
练习:通过结构体数组操作学生成绩
#include#include #include struct student { int sorce; char *name; }; int main() { int i; struct student stu[3]; for(i=0;i


