C++.在将指针的 2D 数组传递到函数时遇到问题
C++.Having trouble passing a 2D array of pointers into a function
我正在制作一个基于文本的小游戏。如果我在 Main 函数中拥有它,我的代码就可以工作,但是当尝试将其放入它自己的函数中时,它会用垃圾数据填充我的字符串,最终导致程序在尝试读取数据时崩溃。
所以这是我的问题,我应该如何将我的 Room 指针的 2D 数组传递到我的函数中,这样我才能得到与将代码保存在主函数中时相同的结果。
以下是当前在我的函数中的代码,当不在函数中时,它可以正常工作。
void InitialiseLevel(int CurrentLevel, Room *Level[2][2]){
if (CurrentLevel == 1){
JumpScareRoom JSRoom1;
Room *room1 = &JSRoom1;
JSRoom1.SetExits("se");
JSRoom1.SetDescriptions("I am a jumpscare room.", "I am a boring room 1");
JSRoom1.SetSouthMessages("There is a door to the SOUTH", "You exit through the SOUTH door.");
JSRoom1.SetEastMessages("There is a door to the EAST", "You exit through the EAST door.");
Room room2;
room2.SetExits("ws");
room2.SetDescriptions("I am a cool room 2", "I am a boring room 2");
Room room3;
room3.SetExits("ne");
room3.SetDescriptions("I am a cool room 3", "I am a boring room 3");
Room room4;
room4.SetExits("wn");
room4.SetDescriptions("I am a cool room 4", "I am a boring room 4");
Level[0][0] = room1;
Level[0][1] = &room2;
Level[1][0] = &room3;
Level[1][1] = &room4;
}
}
我的 main 将数组初始化为
Room *Rooms[2][2] = {};
然后,它使用
InitialiseLevel(1, Rooms); // set up level 1.
我尝试了许多不同的方法,例如使用
void InitialiseLevel(int CurrentLevel, Room **Level[2][2])
和
void InitialiseLevel(int CurrentLevel, Room *(&Level)[2][2])
但是我似乎错过了一些重要的东西。
JumpScareRoom JSRoom1;
是一个本地对象,当您超出函数范围时,它将失效。相反,您可以使用:
JumpScareRoom *pJSRoom1 = new JumpScareRoom();
Room *room1 = JSRoom1;
JSRoom1->SetExits("se");
JSRoom1->SetDescriptions("I am a jumpscare room.", "I am a boring room 1");
JSRoom1->SetSouthMessages("There is a door to the SOUTH", "You exit through the SOUTH door.");
JSRoom1->SetEastMessages("There is a door to the EAST", "You exit through the EAST door.");
...
相关文章:
- 类C++中的函数问题(LNK2019和LNK1120错误)
- 返回不停止函数,递归函数问题?(编程练习,动态规划,Levenshtein 回溯)
- 变分模板递归构造函数问题
- C++函数问题中的数组分配
- C++中嵌套在另一个 LinkedList 中的 LinkedList 整数上的回调函数问题
- C++重载构造函数问题
- 二叉搜索树析构函数问题
- C++ vector<pair<int,int>> std::all_of() 函数问题(重定向到头文件)
- 迷宫构造函数问题 [线程 1:EXC_BAD_ACCESS(代码 = 1,地址 = 0x8)]
- C++函数问题中的 IF 语句
- 函数问题,未定义的引用错误
- C++ 指针无效函数问题
- C++函数问题 = 帮助我理解基本概念
- 由于基于接口的编程,遇到 C++ 虚拟模板函数问题
- C++二进制树递归析构函数问题
- 构造函数问题<无法读取内存>
- 构造函数问题
- C 时间函数问题
- 另一个类中的类的构造函数问题
- C与C++函数问题