c++ - 二维数组更改多个值而只更改一个值

标签 c++ arrays multidimensional-array

我的问题很像这个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/

相关文章:

c++ - 如何在模板类型名上编译时条件?

c++ - ATL c++ 中的文本更改事件

arrays - 如何将结构保存到 Realm ,并包含另一个结构的列表

Python:将大矩阵存储到文本文件中供以后使用

php:将索引二维数组转换为按包含值关联索引的二维数组的最简单方法?

c++ - 是否可以在 C/C++ 中声明全局二维数组?

c++ - VSCode : IDE does not highlight errors in C++ code anymore

c++ - return *this 后调用的析构函数

java - 如何编写一个程序,返回给定值在 Java 整数数组中最后一次出现的索引位置?

python - 将 numpy float 组转换为整数,替换 NaN 值