如何在C中制作一个struct数组? [英] How to make an array of struct in C?

查看:81
本文介绍了如何在C中制作一个struct数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作流氓游戏.我想将地图表示为结构数组,例如在数组中具有256个结构.该地图是一个由16 * 16的图块组成的网格,每个图块都有属性,例如其上方是否有项目.

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.

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

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

推荐答案

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

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

类似地,声明256个struct tiles

Similarly, to declare an array of 256 struct tiles

struct tiles arr[256];  

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

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

这篇关于如何在C中制作一个struct数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆