如何在C中生成结构数组?
我正在做一个类似流氓的游戏。我想将映射表示为一个结构数组,例如,一个数组中有256个结构。地图是一个16*16的分幅网格,每个分幅都有属性,例如是否有一个项目在其顶部 因此,假设我想要一个256个struct如何在C中生成结构数组?,c,arrays,struct,roguelike,C,Arrays,Struct,Roguelike,我正在做一个类似流氓的游戏。我想将映射表示为一个结构数组,例如,一个数组中有256个结构。地图是一个16*16的分幅网格,每个分幅都有属性,例如是否有一个项目在其顶部 因此,假设我想要一个256个structtiles的数组: struct tiles { char type; /* e.g. dirt, door, wall, etc... */ char item; /* item on top of it, if any */ char en
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 main(无效)
{
无符号短整数i;
结构瓷砖[256];
对于(i=1;i您需要为数组指定一个名称。如果int
变量如下所示:
int my_int
int my_ints[256]
struct tiles my_tiles[256]
而int
s的数组如下所示:
int my_int
int my_ints[256]
struct tiles my_tiles[256]
然后,struct tile
的数组如下所示:
int my_int
int my_ints[256]
struct tiles my_tiles[256]
要声明一个struct tiles的数组
只需像对其他类型一样将其放在变量之前。对于10int的数组
int arr[10];
同样,要声明256个struct tile的数组
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;
}
}
int main(无效)
{
无符号短整数i;
结构tiles t_数组[256];
对于(i=0;i<256;++i){
t_数组[i].type=stuff;
t_数组[i].item=morestuff;
t_数组[i].enty=evenmorestuff;
}
}