數組的元素也可以是結構類型的
結構體數組
數組的元素也可以是結構類型的。因此可以構成結構型數組。結構數組的每一個元素都是具有相同結構類型的下標結構變量。在實際應用中,經常用結構數組來表示具有相同數據結構的一個群體。如一個班的學生成績,一個公司員工的工資表等。方法和結構變量相似,只需說明它為數組類型即可。例如:
struct stu{ /*定義結構*/
char num[6];
char name[10];
char sex;
double score;
}stu1[40];
其中數組stu1中的每個數組元素都具有struct stu的結構形式。對結構數組可以作初始化賦值,也可以逐個對每個數組元素賦值。
【例5-16】建立個人通訊錄
分析:程序中定義了一個結構memu,它的成員name、phone和Address分別用來表示姓名、電話號碼和地址。定義結構體數組,在循環中逐個輸入個人通訊信息,最后輸出整個個人通訊錄。
#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;
}
程序運行結果:
input name:
gaoyu↙
input phone:
13787690987↙
input Address:
湖南益陽↙
input name:
chenjie↙
input phone:
13898760987↙
input Address:
湖南衡陽↙
name phone Address
gaoyu 13787690987 湖南益陽
chenjie 13898760987 湖南衡陽