C++ Can';t为二维指针数组的元素赋值。分段故障
编辑:发现错误。不用麻烦了 在我的程序中,我需要初始化C++ Can';t为二维指针数组的元素赋值。分段故障,c++,pointers,segmentation-fault,C++,Pointers,Segmentation Fault,编辑:发现错误。不用麻烦了 在我的程序中,我需要初始化地下城的布局中的房间。由于某些原因,我得到了分段错误,但测试项目中的完全相同的代码运行正常 // RPG.project class Room {}; class Dungeon { public: Dungeon(const int n, const int m) // Dungeon layout is initialized { this->layout = new Room** [n];
地下城的布局中的房间。由于某些原因,我得到了分段错误,但测试项目中的完全相同的代码运行正常
// RPG.project
class Room {};
class Dungeon
{
public:
Dungeon(const int n, const int m) // Dungeon layout is initialized
{
this->layout = new Room** [n];
for ( unsigned int i = 0; i < n; i++ )
layout[i] = new Room* [m];
// All of the rooms are made nullptr as being non-existant at this point.
for ( unsigned int i = 0; i < n; i++ )
{
for ( unsigned int j = 0; j < m; j++ )
{
layout[i][j] = nullptr;
}
}
}
Room*** getLayout() { return this->layout; }
private:
Room*** layout;
};
class Builder
{
private:
Dungeon* dungeon;
public:
void buildRoom(int x, int y) // ERROR here
{
Room*** temp = this->dungeon->getLayout();
temp[x][y] = new Room(); // Segmentation fault error
}
};
//RPG.project
教室{};
班级地牢
{
公众:
地下城(const int n,const int m)//地下城布局已初始化
{
此->布局=新房间**[n];
for(无符号整数i=0;i布局;}
私人:
房间***布局图;
};
类生成器
{
私人:
地牢*地牢;
公众:
void buildRoom(intx,inty)//此处出错
{
房间***温度=此->地下城->getLayout();
temp[x][y]=新房间();//分段错误
}
};
但在其他项目中:
// test.project
class Room
{
};
int main()
{
// Exact same code as in Dungeon and Builder
Room*** layout;
const int n = 3, m = 3;
layout = new Room** [n];
for ( unsigned int i = 0; i < n; i++ )
layout[i] = new Room* [m];
for ( unsigned int i = 0; i < n; i++ ) // All of the rooms are made nullptr
{
for ( unsigned int j = 0; j < m; j++ )
{
layout[i][j] = nullptr;
}
}
layout[0][0] = new Room(); // Somehow works fine.
}
//test.project
教室
{
};
int main()
{
//与《地下城》和《建筑者》中的代码完全相同
房间***布局图;
常数n=3,m=3;
布局=新房间**[n];
for(无符号整数i=0;i
也许你应该停止使用原始指针。。。相反,请使用std::vector
(或者甚至在向量周围使用自定义2D数组类型包装器)请提供一个,猜测一下此->地下城
为空您如何调用buildRoom
?x
和y
的值是多少?x
和y
是否在n
和m
范围内传递给地下城
构造器?还要注意的是,成为a并不是一件需要努力的事情。那么构造器
类是如何使用的?何时何地初始化地下城
指针?如前所述,请将您的问题向我们展示。