1

我不完全确定为什么这段代码会出现段错误。我有一个要创建的对象指针数组。这是我的代码。

   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;
  }
}

可能有人知道我为什么会收到这个段错误吗?我以为我为它分配了内存,因为在创建数组时调用了构造函数谢谢!

4

1 回答 1

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;
  }
}
于 2012-11-18T19:09:49.520 回答