Preface
If you are not familiar with the use of structure variables, you can first read this article by the blogger [C Language] Structure Variable Definition, Initialization, and Usage
1. Define the structure array and initialize it
-
//First declare the structure type
-
struct
students
-
{
-
char name[
20];
-
int age;
-
};
-
-
//Define the structure array and initialize it
-
struct
students stu[
3]={
"Allen",
18,
"Smith",
19,
"Grace",
18};
In order to improve code readability, you can also use { } to group data during initialization (equivalent to the above code)
struct students stu[NUM]={
{
"Allen",18},{
"Smith",19},{
"Grace",18}};
2. Reference structure array
-
printf
( "name age\n\n" );
-
//Loop output
-
for(
int i=
0;i<
3;i++)
-
{
-
printf(
"%s %d\n\n",stu[i].name,stu[i].age);
-
}
The result is as follows:
appendix
The complete test code is as follows:
-
#include <stdio.h>
-
-
# define NUM 3
-
-
int main()
-
{
-
//Declare the structure type
-
struct
students
-
{
-
char name[
20];
-
int age;
-
};
-
-
//Initialize the structure array
-
struct
students stu[NUM]={
{
"Allen",
18},{
"Smith",
19},{
"Grace",
18}};
-
-
//Output
-
printf
( "name age\n\n" );
-
for(
int i=
0;i<NUM;i++)
-
{
-
printf(
"%s %d\n\n",stu[i].name,stu[i].age);
-
}
-
-
return
0;
-
}
The result is as follows:
Original link: https://blog.csdn.net/KinglakeINC/article/details/114242881