在我的程序中有Field和Cell两个类,还有一些继承自Cell的类。Main函数与Field一起工作,Field有一个数组成员,其中包含指向不同类的单元格的指针。这些单元格是在一种方法中创建的,当我试图在另一种方法中访问它们时,会得到Segfault。我觉得肯定有一个错误的数组创建,但不知道如何修复它。我试图将指针数组更改为单元数组,但即使在程序的早期阶段也会出错。
为了避免在这里放太多代码:在主函数中,首先将字段创建为Field myfield;,然后为其调用函数: SetName、SetSize、CreateCells。然后,我尝试使用ConsoleDraw(&myfield);函数来绘制一个字段:
void ConsoleDraw(Field *f)
{
Cell* cell;
for (int i=0; i<f->GetHeight(); i++)
{
for (int j=0; j<f->GetWidth(); j++)
std::cout << f->GetCell(i,j)->GetType();
std::cout << std::endl;
}
std::cout << std::endl;
}下面是类的代码:
Field.h:
class Field
{
public:
//some methods
void ChangeCell(int i, int j, int type);
void CreateCells();
Cell* GetCell(int i, int j);
private:
//some variables
Cell*** cells;
};Field.cpp:
void Field::CreateCells()
{
cells = new Cell**[height];
for (int i=0; i<height; i++)
{
cells[i] = new Cell*[width];
for (int j=0; j<width; j++)
ChangeCell(i,j,0);
}
for (int i=0; i<height; i++)
for (int j=0; j<width; j++)
cells[i][j]->SetNeighb();//operating with variables of single cell
}
void Field::ChangeCell(int i, int j, int type)
{
if (cells[i][j]) delete cells[i][j];
switch (type)
{
case 0:
cells[i][j] = new Cell(0);
break;
case 1:
cells[i][j] = new Cell(1);
break;
case 2:
{
cells[i][j] = new MovingCell;
}
break;
case 3:
{
cells[i][j] = new CreatingCell;
}
break;
case 4:
{
cells[i][j] = new KillingCell;
}
break;
case 5:
{
cells[i][j] = new DyingCell;
}
break;
default:
if (type<10)
{
cells[i][j] = new DyingCell;
cells[i][j]->SetChar(type-4);
}
else
{
cells[i][j] = new MovingCell;
GetCell(i,j)->SetChar(type-10);
}
}
cells[i][j]->SetCoordinates(j,i);
cells[i][j]->SetOwner(this);
}
Cell* Field::GetCell(int i, int j)
{
return cells[i][j]; //Here I got an error.
}我认为没有必要发布Cell类,因为所有问题都出现在与Field的操作中。提前感谢您对正确初始化该数组的任何想法。
发布于 2015-12-21 03:32:34
行if (cells[i][j]) delete cells[i][j];假设所有单元都已使用new进行了分配,但是在下面的switch语句中,有许多情况下单元不是使用new分配的,而是指向共享位置。这在我看来是不干净的,并且肯定会导致段错误。
下一个错误:您在ChangeCell的switch语句的default子句中将指针分配给临时对象。任何对它们的访问迟早都会导致段错误。对它们的任何delete调用都会导致段错误。
https://stackoverflow.com/questions/34384923
复制相似问题