2012-11-18 158 views
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; 
    } 
} 

可能有人知道我爲什麼會收到此段錯誤嗎?我以爲我分配內存,因爲創建數組時調用構造函數謝謝!

+2

使用std :: vector 而不是? – Max

回答

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