温馨提示×

C语言结构体数组怎么创建

小亿
103
2023-12-05 10:55:30
栏目: 编程语言

要创建C语言结构体数组,首先需要定义一个结构体类型,然后使用该类型创建数组。

下面是一个示例代码:

#include <stdio.h>

// 定义结构体类型
struct Student {
    char name[20];
    int age;
    float score;
};

int main() {
    // 创建结构体数组
    struct Student students[3];

    // 初始化结构体数组的元素
    strcpy(students[0].name, "Tom");
    students[0].age = 18;
    students[0].score = 90.5;

    strcpy(students[1].name, "Jerry");
    students[1].age = 19;
    students[1].score = 88.5;

    strcpy(students[2].name, "Alice");
    students[2].age = 20;
    students[2].score = 95.0;

    // 输出结构体数组的元素
    for (int i = 0; i < 3; i++) {
        printf("Name: %s, Age: %d, Score: %.2f\n", students[i].name, students[i].age, students[i].score);
    }

    return 0;
}

在上面的示例代码中,我们首先定义了一个名为Student的结构体类型,包含名字、年龄和分数三个字段。然后,在main函数中,我们使用struct Student students[3];创建了一个包含3个元素的结构体数组。我们通过下标访问结构体数组的元素,并使用.操作符给字段赋值。最后,我们使用循环遍历结构体数组的元素,并使用printf函数输出每个元素的字段值。

运行该程序,输出如下:

Name: Tom, Age: 18, Score: 90.50
Name: Jerry, Age: 19, Score: 88.50
Name: Alice, Age: 20, Score: 95.00

0