2D数组改变了多个值,而只有一个值改变了
2D array changes multiple values while only one changed
我的问题很像这个,在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的值在初始化为'时已经改变了。’而且是假的。请查看数组大小并相应地工作。
相关文章:
- 有一个打印语句的函数是一种糟糕的编程实践吗
- VSCode-有一个红色下划线,但程序构建和运行正确,并且出现配音错误
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 有没有可能有一个只有ADL才能找到的非好友功能
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 我的程序有一个保存配置文件的GUI,如何双击此配置文件以直接加载带有配置数据的GUI?
- 在学习数据结构之前对STL有一个了解是好的吗?
- 我在 .h 中有一个枚举类,并且在.cpp错误中有一个运算符重载:与"运算符<<不匹配
- 如何在 Gnuplot 中分别绘制 2 个文件数据?我有一个文件"sin.txt",另一个文件"cos.txt",我想将它们分别绘制在一个图表上
- 是否可以在C++中有一个"generic"模板参数,该参数可以是非类型模板参数或类型?
- 我的输出中有一个额外的 0,为什么会这样
- 节点是否为空,即使它有一个值?
- 将数组信息存储到 c++ 向量中有一个"Access violation reading location"
- 在 Stream C++ 文本之前有一个额外的换行符
- 我可以有一个 ELI5 作为参考和指针以及何时使用它们吗?
- 在 C++ 中声明 const 对象需要用户定义的默认构造函数.如果我有一个可变成员变量,为什么不呢?
- 我有一个类,它创建了另一个类的实例.如何将变量通过第一个类传递到第二个类的实例化中?
- 如果你有一个固定大小的数组,你需要遍历它!n次,使用二进制搜索如何改变时间复杂性
- 为什么一个函数的末尾有常量这个词,即使它确实改变了一个变量
- 在c++中是否有一个很好的理由在不改变属性的情况下引用它?