繁体   English   中英

2D数组更改多个值,而仅更改一个

[英]2D array changes multiple values while only one changed

我的问题很像这样一个问题在2d数组中设置一个值会导致数组中的其他人改变 ,但是这并不能解决我在这里遇到的问题。

我还试图用2D数组制作一个游戏场,该数组目前充满了“#”。 我试图使左上角成为“。” (但在字段周围留有边框或'#',因此其为1 ,而不是[0] [0])。

但是,到目前为止,我所做的任何尝试始终都会将两个点都变成“。”:

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

这没有任何意义,因为(据我所知)即使在设置map[1][1].symbol = '.';时,我也没有溢出到RAM插槽中的任何地方map[1][1].symbol = '.'; 尽管仅更改了一个位置,但仍将这两个点都标记为“。”。

代码(部分):

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

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

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

首先,您将超出数组的范围。 数组的限制为[mapWidth] [mapHeight]。 但是在初始化循环中,您要迭代[y] [x]-y直到mapHeight和x直到mapWidth。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM