2D阵列更改多个值,而只更改了一个值

时间:2014-06-17 06:30:10

标签: c++ arrays multidimensional-array

我的问题很像Setting a value in a 2d array causes others in array to change,但它并没有解决我的问题。

我也在尝试制作一个2D阵列的游戏领域,目前已经充满了#'#'。我试图让左上角成为'。' (但是在字段周围留下边框或#,'#{3}},而不是[0] [0]。

然而,到目前为止,无论我做了什么,总是将两个点变成'。':

################.###
#.##################
####################
#####D##############
####################
####################
####################
####################
####################
####################
####################
####################
####################
####################
####################

这没有任何意义,因为(据我所知)我没有溢出任何地方进入RAM插槽,即使我设置map[1][1].symbol = '.';它仍然给出这两个点作为& #39;。',但只有一个位置被更改。

代码(部分):

#include <ctime>
#include "stdlib.h"

// Create structure for map tiles
struct mapTile{
    char symbol;
    bool walkable;
};

//Set map Width and Height and create empty array
//I did it like this so I can change the width and height later via ingame menu
int const mapWidth = 20;
int const mapHeight = 15;

mapTile map[mapWidth][mapHeight];

char x = 1;
char y = 1;

void generateField(){
    srand(time(NULL)); //not used yet
    //Set whole field to '#'
    for(int y = 0; y < mapHeight; y++){
        for(int x=0; x < mapWidth; x++){
            map[y][x].symbol = '#';
            map[y][x].walkable = false;
        }
    }
    //Open up route to walk


    map[3][5].symbol = 'D';
    map[y][x].symbol = '.';
    map[y][x].walkable = true;

};

void printField(){
    //print each symbol of the field
    for(int y = 0; y < mapHeight; y++){
        for(int x=0; x < mapWidth; x++){
            cout << map[y][x].symbol;
        }
        cout << endl;
    }
}

2 个答案:

答案 0 :(得分:4)

在两个for循环中,您可以将地图作为[height] [width]访问,但是您将其定义为[width] [height]。

更改它可以解决问题(在我的机器上)。

答案 1 :(得分:2)

首先,你走出了数组的界限。数组的限制是[mapWidth] [mapHeight]。但是在初始化循环中,你正在迭代[y] [x] - y直到mapHeight和x直到mapWidth。

第二个原因是,当你将它初始化为'时,x和y的值已经改变了。和假。请查看阵列大小并相应地工作。

相关问题