数组只能存放一种类型的数据,而结构体内可以存放不同类型的数据。
#include<stdio.h>
#include <string.h> struct Student
{
char name[32];
int age;
int height;
int weight;
}; int main()
{
//结构体赋值
struct Student stu1;
strcpy(stu1.name,"nsal");
stu1.age=45;
stu1.height=150;
stu1.weight=200;
printf("name=%s\n",stu1.name);
//结构体赋值
struct Student stu2={"hhh",12,45,45};
//结构体数组
//int arr[3]={1,2,3};
struct Student Stus[3]={
{"hhh",12,45,45},
{"ttt",16,24,45},
{"kkk",18,23,45},
};
//遍历结构体数组
int size=sizeof(Stus)/sizeof(Stus[0]);
for(int i=0;i<size;i++)
{
printf("name=%s\n",Stus[i].name);
}
return 0;
}
输出结果:
name=nsal
name=hhh
name=ttt
name=kkk
结构体的使用很简单,但是细节往往很容易忽略,例如结构体最后很容易少掉;结构体变量也是以;分开