C语言结构体数组 #
一、结构体数组定义 #
1.1 基本语法 #
c
struct Student {
char name[20];
int age;
};
struct Student class[30];
1.2 使用typedef #
c
typedef struct {
char name[20];
int age;
} Student;
Student class[30];
二、初始化 #
2.1 完全初始化 #
c
Student class[3] = {
{"Alice", 20},
{"Bob", 21},
{"Charlie", 19}
};
2.2 部分初始化 #
c
Student class[3] = {
{"Alice", 20}
};
三、访问元素 #
3.1 访问成员 #
c
#include <stdio.h>
typedef struct {
char name[20];
int age;
} Student;
int main() {
Student class[3] = {
{"Alice", 20},
{"Bob", 21},
{"Charlie", 19}
};
for (int i = 0; i < 3; i++) {
printf("%s: %d岁\n", class[i].name, class[i].age);
}
return 0;
}
四、总结 #
| 操作 | 语法 |
|---|---|
| 定义 | Student arr[n]; |
| 初始化 | {{…}, {…}} |
| 访问 | arr[i].成员 |
下一步,让我们学习结构体指针!
最后更新:2026-03-26