前言
如果对结构体变量的使用不太熟悉,可以先看看博主的这篇文章【C语言】结构体变量定义、初始化、使用
一、定义结构体数组,并初始化
-
//首先声明结构体类型
-
struct
students
-
{
-
char name[
20];
-
int age;
-
};
-
-
//定义结构体数组,并初始化
-
struct
students stu[
3]={
"Allen",
18,
"Smith",
19,
"Grace",
18};
为了提高代码可读性,在初始化时,也可以用 { } 将数据分组(与上述代码等价)
struct students stu[NUM]={
{
"Allen",18},{
"Smith",19},{
"Grace",18}};
二、引用结构体数组
-
printf(
"姓名 年龄\n\n");
-
//循环输出
-
for(
int i=
0;i<
3;i++)
-
{
-
printf(
"%s %d\n\n",stu[i].name,stu[i].age);
-
}
结果如下:
附录
完整测试代码如下:
-
#include <stdio.h>
-
-
#define NUM 3
-
-
int main()
-
{
-
//声明结构体类型
-
struct
students
-
{
-
char name[
20];
-
int age;
-
};
-
-
//初始化结构体数组
-
struct
students stu[NUM]={
{
"Allen",
18},{
"Smith",
19},{
"Grace",
18}};
-
-
//输出
-
printf(
"姓名 年龄\n\n");
-
for(
int i=
0;i<NUM;i++)
-
{
-
printf(
"%s %d\n\n",stu[i].name,stu[i].age);
-
}
-
-
return
0;
-
}
结果如下:
原文链接:https://blog.csdn.net/KinglakeINC/article/details/114242881