1.结构体的一般形式为:
struct 结构体名
{
数据类型 成员名1;
数据类型 成员名2;
:
数据类型 成员名n;
};
2.结构体的定义及赋值
1》先定义结构体类型再定义变量名,这是C语言中定义结构体类型变量最常见的方式。
struct 结构体名
{
成员列表;
};
struct 结构体名 变量名;
eg:
struct student
{
int SID;
char name[N];
float score;
}
int main()
{
//定义结构体类型后赋值
struct student s1,s2,s3;
strcpy(s1.name,"s1");
s1.SID=1;
s1.score=89;
//
strcpy(s2.name,"s2");
s2.SID=2;
s2.score=87;
}
2》在定义类型的同时定义变量。
这种形式的定义的一般形式为:
struct 结构体名
{
成员列表;
}变量名;
eg:
struct student
{
int SID;
char name[N];
float score;
} s4={4,"dd",90},s5={5,"ee",99};
3》直接定义结构类型变量
其一般形式为:
struct //没有结构体名
{
成员列表;
}变量名;
实例源代码:
#include<stdio.h>
#include<string.h>
#define N 10
struct student
{
int SID;
char name[N];
float score;
} s4={4,"dd",90},s5={5,"ee",99};
int main()
{
//定义结构体类型后赋值
struct student s1,s2,s3;
strcpy(s1.name,"s1");
s1.SID=1;
s1.score=89;
//
strcpy(s2.name,"s2");
s2.SID=2;
s2.score=87;
// 同一结构体类型的结构变量之间可以互相赋值
s3=s2;
s3.SID=3;
printf(" %d %s %.2f\n",s1.SID,s1.name,s1.score);
printf(" %d %s %.2f\n",s2.SID,s2.name,s2.score);
printf(" %d %s %.2f\n",s3.SID,s3.name,s3.score);
printf(" %d %s %.2f\n",s4.SID,s4.name,s4.score);
return 0;
}
运行效果:
![](https://i-blog.csdnimg.cn/blog_migrate/ba5d0fed049867d4534175decae5231f.png)