C言語で構造体配列を作成の方法

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 という構造体型を定義しており、名前、年齢、得点という3つのフィールドが含まれています。次に、main関数で struct Student students[3]; を使用して3つの要素を含む構造体配列を作成しました。構造体配列の要素には添え字でアクセスし、.演算子を使用してフィールドに値を代入しています。最後に、forループを使用して構造体配列の要素を反復処理し、printf関数を使用して各要素のフィールド値を出力しています。

プログラムを実行すると以下の出力が得られます。

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