C语言 结构体数组的初始化
与普通数组一样,结构数组也可以在定义时进行初始化。初始化的格式为:
结构数组[n] = {{初值表1},{初值表2},…, {初值表n}}
例如:
struct student
{
int sno;
char sname[10];
int sage;
char depmt [20];
float cscore;
};
struct student s [3]={{1001,"zhangsan",21,"computer".78},
(1003,"lisi",19,"computer",88),
{1003,"wangwu",20,"computer",76));
如果一个结构体数组中所有数组元素的值都是一样的,也可以采用如下形式初始化:
struct student s[3]={{1001,"zhangsan",21,"computer",78}};
有三个数组元素,但只有一个初值表,那么三个元素的值全部一样,使用for循环语句将三个元素输出:
main()
{
struct student s[3]={{1OOl,"zhangsan",21,"computer",78}};
int i;
for(i=O;i<3;i++)
{
printf("%d %10s ",s[0].sno,s[0].sname);
printf("%d %20s %f\n",s[0].sage,s[0].depmt,s[0].cscore );
}
}
程序执行,输出结果为:
1001 zhangsan 21 computer 78.000000
1001 zhangsan 21 computer 78.000000
1001 zhangsan 21 computer 78.000000
结构体数组的初始化不允许使用省略初值,只给出大括号的形式:
struct student s[3]={{1001,"zhangsan",21,"computer",78},(),()};
如果给出全部的初值表,结构体数组元素的个数可以省略,即可以写成以下形式:
struct student s[]={{…},{…},{…});
点击加载更多评论>>