C++.在将指针的 2D 数组传递到函数时遇到问题

C++.Having trouble passing a 2D array of pointers into a function

本文关键字:函数 问题 遇到 数组 指针 2D C++      更新时间:2023-10-16

我正在制作一个基于文本的小游戏。如果我在 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.");
...