数组元素也可以使结构类型,可以构成结构类型数组。结构类型数组的每一个元素都是具有相同结构类型的下标结构类型变量。经常用结构类型数组来表示具有相同结构的一个群体,如一个班的学生信息,一个车间的职工信息等
1结构类型数组的宏定义
结构类型数组的定义方法和结构类型变量相似,只需定义它为数组类型即可,例如
#define N 3
struct StudentType
{
int num;
char *name;
struct StudentType
{
int num;
char *name;
char sex[3];
int age;
float score;
}student[]=
{
{10101,"","",42,98.1},
{10102,"","",22,99.8},
{10103,"","",43,96.5}
};
struct StudentType
{
int num;
char *name;
char sex[3];
int age;
float score;
}student[N];
或者是把结构类型名省略掉
struct
{
int num;
char *name;
char sex[3];
int age;
float score;
}student[N];
2结构类型数组的初始化
#include <stdio.h>
#include <stdlib.h>
#define N 3
int main(void)
{
int i;
struct StudentType
{
int num;
char *name;
char sex[3];
int age;
float score;
};
struct StudentType student[N]=
{
{10101,"µÂ»ªÁõ","ÄÐ",42,98.1},
{10102,"ÅíÓ°ÕÅ","Å®",22,99.8},
{10103,"ѧÓÑÕÅ","ÄÐ",43,96.5}
};
for(i=0;i<N;i++)
{
printf("%8d",student[i].num);
printf("%12s",student[i].name);
printf("%6s",student[i].sex);
printf("%6d",student[i].age);
printf("%8.1f\n",student[i].score);
}
system("PAUSE");
return 0;
}
定义结构类型数组时,也可不指定元素个数,例如
struct StudentType student[]=
{
{10101,"µÂ»ªÁõ","ÄÐ"£¬42,98.1}£¬
{10102,"ÅíÓ°ÕÅ","Å®"£¬22,99.8},
{10103,"ѧÓÑÕÅ","ÄÐ",43,96.5}
};
在编译时,系统将根据初始结构个数自动的确定数组元素个数,当然也可以采用直接定义结构类型数组并初始化的形式
struct StudentType
{
int num;
char *name;
char sex[3];
int age;
float score;
}student[]=
{
{10101,"","",42,98.1},
{10102,"","",22,99.8},
{10103,"","",43,96.5}
};
或者
struct
{
int num;
char *name;
char sex[3];
int age;
float score;
}student[]=
{
{10101,"µÂ»ªÁõ","ÄÐ"£¬42,98.1},
{10102,"ÅíÓ°ÕÅ","Å®"£¬22,99.8},
{10103,"ѧÓÑÕÅ","ÄÐ",43,96.5}
}