數(shù)組的元素也可以是結(jié)構(gòu)類型的
結(jié)構(gòu)體數(shù)組
數(shù)組的元素也可以是結(jié)構(gòu)類型的。因此可以構(gòu)成結(jié)構(gòu)型數(shù)組。結(jié)構(gòu)數(shù)組的每一個元素都是具有相同結(jié)構(gòu)類型的下標結(jié)構(gòu)變量。在實際應用中,經(jīng)常用結(jié)構(gòu)數(shù)組來表示具有相同數(shù)據(jù)結(jié)構(gòu)的一個群體。如一個班的學生成績,一個公司員工的工資表等。方法和結(jié)構(gòu)變量相似,只需說明它為數(shù)組類型即可。例如:
struct stu{ /*定義結(jié)構(gòu)*/
char num[6];
char name[10];
char sex;
double score;
}stu1[40];
其中數(shù)組stu1中的每個數(shù)組元素都具有struct stu的結(jié)構(gòu)形式。對結(jié)構(gòu)數(shù)組可以作初始化賦值,也可以逐個對每個數(shù)組元素賦值。
【例5-16】建立個人通訊錄
分析:程序中定義了一個結(jié)構(gòu)memu,它的成員name、phone和Address分別用來表示姓名、電話號碼和地址。定義結(jié)構(gòu)體數(shù)組,在循環(huán)中逐個輸入個人通訊信息,最后輸出整個個人通訊錄。
#include"stdio.h"
#define N 2
int main()
{
struct memu{
char name[20];
char phone[11];
char Address[50];
}person[N];
int i;
for(i=0;i<N;i++)
{
printf("input name:\n");
gets(person[i].name);
printf("input phone:\n");
gets(person[i].phone);
printf("input Address:\n");
gets(person[i].Address);
}
printf("name\t\tphone\t\tAddress\n");
for(i=0;i<N;i++)
printf("%s\t\t%s\t\t%s\n",person[i].name,person[i].phone,person[i].Address);
return 0;
}
程序運行結(jié)果:
input name:
gaoyu↙
input phone:
13787690987↙
input Address:
湖南益陽↙
input name:
chenjie↙
input phone:
13898760987↙
input Address:
湖南衡陽↙
name phone Address
gaoyu 13787690987 湖南益陽
chenjie 13898760987 湖南衡陽