易百教程

创建结构体数组

结构体数组声明如下:

struct scores { 
       char name[32]; 
       int score; 
}; 

struct scores player[4];

该语句声明了一个scores结构体数组,数组的名称为player,它包含四个结构变量作为其元素。

通过使用数组和结构表示法的组合来访问数组中的成员。例如:

player[2].name

该变量访问player结构数组中第三个元素中的name成员。

示例代码

#include <stdio.h> 

int main() 
{
    struct scores
    {
        char name[32];
        int score;
    };
    struct scores player[4];
    int x;

    for (x = 0; x < 4; x++)
    {
        printf("Enter player %d: ", x + 1);
        scanf("%s", player[x].name);
        printf("Enter their score: ");
        scanf("%d", &player[x].score);
    }

    puts("Player Info");
    printf("#\tName\tScore\n");
    for (x = 0; x < 4; x++)
    {
        printf("%d\t%s\t%5d\n",
            x + 1, player[x].name, player[x].score);
    }
    system("pause");
    return(0);
}

执行上面示例代码,得到以下结果:

Enter player 1: Curry
Enter their score: 197
Enter player 2: Kobe
Enter their score: 198
Enter player 3: Duland
Enter their score: 198
Enter player 4: James
Enter their score: 201
Player Info
#       Name    Score
1       Curry     197
2       Kobe      198
3       Duland    198
4       James     201