我的问题很像这个Setting a value in a 2d array causes others in array to change ,但是它并没有解决我这里的问题。
我也在尝试制作一个带有二维数组的游戏场,目前全是“#”。我想让左上角变成“。” (但在字段周围留下边框或“#”,所以它是 1,而不是 [0][0])。
但是,到目前为止,无论我尝试过什么,总是将两个点变成“.”:
################.###
#.##################
####################
#####D##############
####################
####################
####################
####################
####################
####################
####################
####################
####################
####################
####################
这没有任何意义,因为(据我所知)我没有溢出到 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] 访问 map ,但是您将其定义为 [width][height]。
更改它可以解决问题(在我的机器上)。
关于c++ - 二维数组更改多个值而只更改一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24257073/