2D数组改变了多个值,而只有一个值改变了

2D array changes multiple values while only one changed

本文关键字:改变 有一个 数组 2D      更新时间:2023-10-16

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

我也试图使一个游戏领域与一个2D数组,目前充满了"#"。我试着让左上角变成'。(但在字段周围留下一个边框或"#",所以它是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],但是你定义它为[width][height]。

在我的机器上改变它就解决了问题。

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

第二个原因是,x和y的值在初始化为'时已经改变了。’而且是假的。请查看数组大小并相应地工作。

相关文章: