C语言结构体数组的使用
定义和初始化:
在C语言中,结构体数组是一个连续的内存区域,存储相同类型结构体元素的集合。要定义一个结构体数组,需要使用以下语法:
<code class="c">struct structure_name array_name[array_size];</code>
其中,
structure_name是结构体的名称,
array_name是数组的名称,
array_size是数组的元素个数。
立即学习“C语言免费学习笔记(深入)”;
访问元素:
结构体数组中的元素可以通过下标访问,如下所示:
<code class="c">array_name[index].member_name;</code>
其中,
index是元素的索引,
member_name是结构体成员的名称。
示例:
以下示例演示了如何使用结构体数组来存储学生信息:
<code class="c">#include <stdio.h>
struct student {
int roll_no;
char name[20];
float marks;
};
int main() {
struct student students[3];
// 初始化数组元素
students[0].roll_no = 1;
strcpy(students[0].name, "John");
students[0].marks = 85.0;
students[1].roll_no = 2;
strcpy(students[1].name, "Mary");
students[1].marks = 90.0;
students[2].roll_no = 3;
strcpy(students[2].name, "Bob");
students[2].marks = 75.0;
// 访问数组元素
printf("Student 1:\n");
printf("Roll No: %d\n", students[0].roll_no);
printf("Name: %s\n", students[0].name);
printf("Marks: %.2f\n\n", students[0].marks);
return 0;
}</code> 