C語(yǔ)言 結(jié)構(gòu)體數(shù)組的初始化
與普通數(shù)組一樣,結(jié)構(gòu)數(shù)組也可以在定義時(shí)進(jìn)行初始化。初始化的格式為:
結(jié)構(gòu)數(shù)組[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));
如果一個(gè)結(jié)構(gòu)體數(shù)組中所有數(shù)組元素的值都是一樣的,也可以采用如下形式初始化:
struct student s[3]={{1001,"zhangsan",21,"computer",78}};
有三個(gè)數(shù)組元素,但只有一個(gè)初值表,那么三個(gè)元素的值全部一樣,使用for循環(huán)語(yǔ)句將三個(gè)元素輸出:
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 );
}
}
程序執(zhí)行,輸出結(jié)果為:
1001 zhangsan 21 computer 78.000000
1001 zhangsan 21 computer 78.000000
1001 zhangsan 21 computer 78.000000
結(jié)構(gòu)體數(shù)組的初始化不允許使用省略初值,只給出大括號(hào)的形式:
struct student s[3]={{1001,"zhangsan",21,"computer",78},(),()};
如果給出全部的初值表,結(jié)構(gòu)體數(shù)組元素的個(gè)數(shù)可以省略,即可以寫成以下形式:
struct student s[]={{…},{…},{…});
點(diǎn)擊加載更多評(píng)論>>