[英]2D array changes multiple values while only one changed
My question is much like this one Setting a value in a 2d array causes others in array to change , however it does not solve what I have here. 我的问题很像这样一个问题在2d数组中设置一个值会导致数组中的其他人改变 ,但是这并不能解决我在这里遇到的问题。
I am also trying to make a game field with a 2D array, currently full of '#'. 我还试图用2D数组制作一个游戏场,该数组目前充满了“#”。 I am trying to get the top left corner to become '.' 我试图使左上角成为“。” (but leaving a border or '#' around the field, so its 1 , not [0][0]). (但在字段周围留有边框或'#',因此其为1 ,而不是[0] [0])。
However, whatever I tried so far always turns two spots into '.': 但是,到目前为止,我所做的任何尝试始终都会将两个点都变成“。”:
################.###
#.##################
####################
#####D##############
####################
####################
####################
####################
####################
####################
####################
####################
####################
####################
####################
This doesn't make any sense, since (as far as I can see) I am not overflowing anywhere into a RAM slot, and even when I set map[1][1].symbol = '.';
这没有任何意义,因为(据我所知)即使在设置map[1][1].symbol = '.';
时,我也没有溢出到RAM插槽中的任何地方map[1][1].symbol = '.';
it still gives those two spots as '.', though there is only one location being changed. 尽管仅更改了一个位置,但仍将这两个点都标记为“。”。
Code (partial): 代码(部分):
#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;
}
}
In both your for-loops you access the map as [height][width], however you define it as [width][height]. 在两个for循环中,您都以[height] [width]访问该地图,但是将其定义为[width] [height]。
Changing it solves the problem (on my machine). 更改它可以解决问题(在我的机器上)。
first of all you are going out of the bounds of the array. 首先,您将超出数组的范围。 The limit of your array is [mapWidth][mapHeight]. 数组的限制为[mapWidth] [mapHeight]。 But in the initialization loop you are iterating the [y][x] - y till mapHeight and x till mapWidth. 但是在初始化循环中,您要迭代[y] [x]-y直到mapHeight和x直到mapWidth。
And the second reason is, the value of x and y has already changed when you are initializing it to '.' 第二个原因是,将x和y的值初始化为'时,已经改变了。 and false. 和错误。 Please see the array size and work accordingly. 请查看阵列大小并相应地工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.