C 编程中的结构数组是不同数据类型变量的集合,在单个名称下组合在一起。
结构声明的一般形式
结构声明如下:
struct tagname{
datatype member1;
datatype member2;
datatype member n;
};
在这里,struct 是关键字
TagName 指定结构的名称
member1、member2 指定构成结构的数据项。
例
以下示例显示了 C 编程中结构数组的用法
struct book{
int pages;
char author [30];
float price;
};
结构阵列
在 C 编程中,结构最常见的用法是结构数组。
要声明结构数组,首先必须定义结构,然后定义该类型的数组变量。
例如: − struct book b[10]; //“book”类型结构数组中的 10 个元素
扫描二维码关注公众号,回复: 17487851 查看本文章![]()
例
以下程序显示了结构数组的用法。
#include <stdio.h>
#include <string.h>
struct student{
int id;
char name[30];
float percentage;
};
int main(){
int i;
struct student record[2];
// 1st student's record
record[0].id=1;
strcpy(record[0].name, "Bhanu");
record[0].percentage = 86.5;
// 2nd student's record
record[1].id=2;
strcpy(record[1].name, "Priya");
record[1].percentage = 90.5;
// 3rd student's record
record[2].id=3;
strcpy(record[2].name, "Hari");
record[2].percentage = 81.5;
for(i=0; i<3; i++){
printf(" Records of STUDENT : %d
", i+1);
printf(" Id is: %d
", record[i].id);
printf(" Name is: %s
", record[i].name);
printf(" Percentage is: %f
",record[i].percentage);
}
return 0;
}
输出
当执行上述程序时,它会产生以下结果 -
Records of STUDENT : 1
Id is: 1
Name is: Bhanu
Percentage is: 86.500000
Records of STUDENT : 2
Id is: 2
Name is: Priya
Percentage is: 90.500000
Records of STUDENT : 3
Id is: 3
Name is: Hari
Percentage is: 81.500000