如何在C中制作一个结构数组?

How to make an array of struct in C?

我正在制作一款roguelike游戏。我想将地图表示为一个结构数组,例如一个数组中有 256 个结构。地图是一个16*16的格子格子,每个格子都有属性,比如上面是否有物品

所以说我想要一个结构为 256 的数组 tiles:

struct tiles {
        char type; /* e.g. dirt, door, wall, etc... */
        char item; /* item on top of it, if any */
        char enty; /* entity on top of it, e.g. player, orc if any */
}

然后,我需要访问这样的结构数组:

int main(void)
{
        unsigned short int i;
        struct tiles[256];

        for (i = 1; i <= 256; i++) {
                struct tiles[i].type = stuff;
                struct tiles[i].item = morestuff;
                struct tiles[i].enty = evenmorestuff;
        }
}

您需要为数组命名。如果 int 变量看起来像:

int my_int

int 的数组如下所示:

int my_ints[256]

然后 struct tiles 的数组看起来像:

struct tiles my_tiles[256]

要声明一个 struct tiles 的数组,只需像处理其他类型一样将它放在变量之前。对于 10 int

的数组
int arr[10];  

同理声明一个256的数组struct tiles

struct tiles arr[256];  

要访问 arr 元素的任何成员,例如 type,您需要 . 运算符作为 arr[i].type

数组是一个变量,就像一个整数,所以你需要给它一个名字才能访问它。

注意:数组的最低索引为0,最高索引为255,所以for循环应该是:for (i = 0; i < 256; ++i)代替。

int main(void)
{
        unsigned short int i;
        struct tiles t_array[256];

        for (i = 0; i < 256; ++i) {
                t_array[i].type = stuff;
                t_array[i].item = morestuff;
                t_array[i].enty = evenmorestuff;
        }
}