我不完全确定为什么我会为这段代码获得段错误。我有一个我想要创建的对象指针数组。这是我的代码。
edge **test = new edge*[a]; //Edge is a predefined class I have created. a is a my size of my array.
graphCreate2(test, vertices, roads, a); //Note roads is an edge class I have already created also
然而,当我尝试访问edge ** test的元素时,我得到了一个段错误。以下是我访问它的方式。
void graphCreate2(edge **test, int vertices, edge *roads, int a)
{
for(int i = 0; i < a; i++)
{
e[i]->setEdgeSrc(roads[i].getEdgeSrc());
e[i]->setEdgeDes(roads[i].getEdgeDes());
e[i]->setLength(roads[i].getLength());
cout << e[i]->getLength() << " " << e[i]->getEdgeSrc() << " " << endl;
}
}
可能有人知道我为什么会遇到这个段错误?我以为我在创建数组时调用构造函数时为它分配了内存谢谢!
答案 0 :(得分:3)
为每个edge
调用构造函数 。你只是在创建指针数组,但它们指向垃圾。
你需要在循环中创建它们。
void graphCreate2(edge **test, int vertices, edge *roads, int a)
{
for(int i = 0; i < a; i++)
{
test[i] = new edge(); // create the edge
test[i]->setEdgeSrc(roads[i].getEdgeSrc());
test[i]->setEdgeDes(roads[i].getEdgeDes());
test[i]->setLength(roads[i].getLength());
cout << test[i]->getLength() << " " << test[i]->getEdgeSrc() << " " << endl;
}
}