在 C 语言 中,数组 可以存放任意的 数据类型,比如 int、long、dobule,也可以存放 结构体,存放结构体的数组,我们称为结构体数组。
struct structName arrName[len];
我们定义了一个结构体数组 arrName,该数组中每一个元素的类型都是一个 structName 类型的结构体,数组的长度为 len。
C 语言结构体数组定义与使用
#include <stdio.h>
struct Student{
char *name;
float score;
};
void main()
{
printf("嗨客网(www.haicoder.net)\n\n");
struct Student students[3];
students[0].name = "HaiCoder";
students[0].score = 89.5;
students[1].name = "zwl";
students[1].score = 99;
students[2].name = "pbj";
students[2].score = 80;
int i = 0;
for (i = 0; i < 3; i++)
{
printf("Stu name = %s, score = %f\n", students[i].name, students[i].score);
}
printf("\n");
return 0;
}
程序运行后,控制台输出如下图所示:
我们首先,定义了一个结构体 Student,该结构体有两个成员,即一个 字符串 类型的 name 和一个 float 类型 的 score。
接着,我们定义了一个结构体类型的数组 students,该结构体数组的长度为 3,接着,我们分别给这数组中的三个成员的每一个字段进行赋值。
最后,我们使用了 for 循环 打印了结构体中的每一个成员的每一个字段的值。
C 语言结构体数组定义与使用
#include <stdio.h>
struct Student{
char *name;
float score;
};
void main()
{
printf("嗨客网(www.haicoder.net)\n\n");
struct Student students[5] = {
{"HaiCoder", 99},
{"zwl", 90},
{"zll", 80},
{"pbj", 78},
{"ymj", 60}
};
int totalScore = 0;
int avgScore = 0;
int i = 0;
for (i = 0; i < 5; i++)
{
totalScore += students[i].score;
}
avgScore = totalScore / 5;
printf("Student Total Score = %d, AvgScore = %d\n", totalScore, avgScore);
printf("\n");
return 0;
}
程序运行后,控制台输出如下图所示:
我们定义了一个结构体数组,并初始化了该结构体数组,最后,我们使用了 for 循环遍历了该结构体数组中的每一个成员,并将成员中的 score 字段全部相加,最后,求出了总分和平均分。
在 C 语言中,数组可以存放任意的数据类型,比如 int、long、dobule,也可以存放结构体,存放结构体的数组,我们称为结构体数组。