gpt4 book ai didi

C++。将二维指针数组传递到函数时遇到问题

转载 作者:行者123 更新时间:2023-11-30 19:41:49 25 4
gpt4 key购买 nike

我正在制作一个基于文本的小型游戏。如果我将它放在主函数中,我的代码就可以工作,但是当尝试将其放入它自己的函数中时,它会用垃圾数据填充我的字符串,最终导致程序在尝试读取数据时崩溃。

所以这是我的问题,我应该如何将 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++。将二维指针数组传递到函数时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33130895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com