结构体struct也是一种数据类型,它也可以作为数组元素的类型
结构数组定义
定义形式:
struct 结构名称{
成员列表
}数组名称[元素个数];
struct Student{
char name[20];
short num;
float score;
}sar[2]; //有2两个元素的结构数组
结构数组初始化:
struct Student{ //Student为结构体名称
char name[20]; //学生姓名
int num; //学生学号
float score; //学生成绩
};
//定义并初始化
struct Student st[4] = { //只给st第1、2个元素赋值
{"王二狗", 1001123, 68.5},
{"李小花", 1001125, 76.2}
};
//指定元素赋值(须强制转换以区分数组)。给第3个元素赋值
st[2] = (struct Student){
"张四",
1001126,
98
};
//成员逐个赋值。给第4个元素赋值
strcpy(st[3].name, "陈六");
st[3].num = 1001127;
st[3].score = 50.5;
//st长度
int len = sizeof(st) / sizeof(struct Student);
printf("st size:%zu\n", sizeof(st));
for(int i = 0; i < len; i++){
printf("姓名:%s\t学号:%d\t成绩:%f\n", st[i].name, st[i].num, st[i].score);
}
#include <stdio.h>
#include <string.h>
/*
时间:2022-05-11 18:47
作者:sgbl888
功能:结构数组
知识点:
1、
2、
3、
*/
struct Student{ //Student为结构体名称
char name[20]; //学生姓名
int num; //学生学号
float score; //学生成绩
};
int main(){
//定义并初始化
struct Student st[4] = { //只给st第1、2个元素赋值
{"王二狗", 1001123, 68.5},
{"李小花", 1001125, 76.2}
};
//指定元素赋值(须强制转换以区分数组)。给第3个元素赋值
st[2] = (struct Student){
"张四",
1001126,
98
};
//成员逐个赋值。给第4个元素赋值
strcpy(st[3].name, "陈六");
st[3].num = 1001127;
st[3].score = 50.5;
//st长度
int len = sizeof(st) / sizeof(struct Student);
printf("st size:%zu\n", sizeof(st));
for(int i = 0; i < len; i++){
printf("姓名:%s\t学号:%d\t成绩:%f\n", st[i].name, st[i].num, st[i].score);
}
return 0;
}
运行结果:
st size:112
姓名:王二狗 学号:1001123 成绩:68.500000
姓名:李小花 学号:1001125 成绩:76.199997
姓名:张四 学号:1001126 成绩:98.000000
姓名:陈六 学号:1001127 成绩:50.500000