How to make an array of struct in C?

前提是你 提交于 2019-11-29 23:32:39

问题


I am making a roguelike game. I want to represent the map as an array of structs, for example having 256 structs in an array. The map is a 16*16 grid of tiles, and each tile has attributes, such as whether there is an item on top of it.

So say that I want an array of 256 of the struct 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 */
}

Then, I need to access an array of that structs something like this:

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;
        }
}

回答1:


To declare an array of struct tiles just place this before the variable as you do with other types. For an array of 10 int

int arr[10];  

Similarly, to declare an array of 256 struct tiles

struct tiles arr[256];  

To access any member, say type, of elements of arr you need . operator as arr[i].type




回答2:


You need to give your array a name. If an int variable looks like:

int my_int

And an array of ints looks like:

int my_ints[256]

Then an array of struct tiles looks like:

struct tiles my_tiles[256]



回答3:


An array is a variable, just like an integer, so you need to give it a name to access it.

Note: the array has a lowest index of 0 and a highest index of 255, so the for loop should be: for (i = 0; i < 256; ++i) instead.

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;
        }
}


来源:https://stackoverflow.com/questions/32185751/how-to-make-an-array-of-struct-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!