结构体数组是一种特殊类型的数组,每个数组元素都是一个完整的结构体,包含结构体的所有成员。结构体数组声明与定义的方式包括:
-
先定义结构体类型,再定义结构体数组。语法格式:
struct 标签或者结构体名
{
数据类型 成员1;
数据类型 成员2;
...
数据类型 成员n;
};
struct 标签或者结构体名 数组名[数组长度];
代码示例:
#include <stdio.h>
#include <string.h>
// 定义结构体类型
struct Student
{
char name[20];
unsigned short age;
float score;
};
// 定义结构体数组
struct Student students[3];
// 初始化结构体数组
int main()
{
// 逐个赋值
strcpy(students[0].name, "张三");
students[0].age = 20;
students[0].score = 90.5f;
strcpy(students[1].name, "李四");
students[1].age = 21;
students[1].score = 89.0f;
strcpy(students[2].name, "王五");
students[2].age = 23;
students[2].score = 79.0f;
for (int index = 0; index < 3; ++index)
{
printf("该学生的基本信息:%s, %u, %.1f\n", students[index].name, students[index].age, students[index].score);
}
return 0;
}
-
定义结构体类型的同时定义结构体数组。语法格式:
struct 标签或者结构体名
{
数据类型 成员1;
数据类型 成员2;
...
数据类型 成员n;
} 数组名[数组长度];
代码示例:
#include <stdio.h>
#include <string.h>
// 定义结构体类型
struct Student
{
char name[20];
unsigned short age;
float score;
} students[3];
// 初始化结构体数组
int main()
{
// 逐个赋值
strcpy(students[0].name, "张三");
students[0].age = 20;
students[0].score = 90.5f;
strcpy(students[1].name, "李四");
students[1].age = 21;
students[1].score = 89.0f;
strcpy(students[2].name, "王五");
students[2].age = 23;
students[2].score = 79.0f;
for (int index = 0; index < 3; ++index)
{
printf("该学生的基本信息:%s, %u, %.1f\n", students[index].name, students[index].age, students[index].score);
}
return 0;
}
-
只通过结构体成员来定义结构体数组。语法格式:
struct
{
数据类型 成员1;
数据类型 成员2;
...
数据类型 成员n;
} 数组名[数组长度];
代码示例:
#include <stdio.h>
#include <string.h>
// 定义结构体类型
struct Student
{
char name[20];
unsigned short age;
float score;
} students[3] = {
{"张三", 20, 90.5f},
{"李四", 21, 89.0f},
{"王五", 23, 79.0f}
};
// 初始化结构体数组
int main()
{
for (int index = 0; index < 3; ++index)
{
printf("该学生的基本信息:%s, %u, %.1f\n", students[index].name, students[index].age, students[index].score);
}
return 0;
}