2014-09-26 52 views
0

我沒有收到任何編譯錯誤,當我嘗試使用另一個類的一個類指針數組執行此操作時,我也沒有收到任何錯誤。當我用三節課來做時。我崩潰了。段類指針的分段錯誤另一個類的類指針數組的數組

#define size 10 

// single point with x and y 
class singlePoint{ 
public: 
    float xCoordinate; 
    float yCoordinate; 
}; 

// row of points 
class pointRow{ 
public: 
    singlePoint *pointRowArray[size]; 
    void makePointRowArray(int);  
    void setPointRowArray(int); 
}; 

// 「row」 of row of points 
class totalSquare{ 
public: 
    pointRow *totalSquareArray[size]; 
    void makeTotalSquare(int); 
    void setTotalSquare(int); 
}; 
//----------------- 
void pointRow::makePointRowArray(int rowSize){ 
    for (int i = 0; i < rowSize; i++){ 
     pointRowArray[i] = new singlePoint; 
    } 
} 

void pointRow::setPointRowArray(int rowSize){ 
    for (int i = 0; i < rowSize; i++){ 
     pointRowArray[i]->xCoordinate = 11; 
     pointRowArray[i]->yCoordinate = 12; 
    } 
} 

void totalSquare::makeTotalSquare(int collumnSize){ 
    for (int i = 0; i < collumnSize; i++){ 
     totalSquareArray[i] = new pointRow; 
    } 
} 

void totalSquare::setTotalSquare(int collumnSize){ 
    for (int collumnSet = 0; collumnSet < collumnSize; collumnSet++){ 
     for (int rowSet = 0; rowSet < collumnSize; rowSet++){ 
      // my problem lies somewhere in here 
      totalSquareArray[collumnSet]->pointRowArray[rowSet]->xCoordinate = 13; 
      totalSquareArray[collumnSet]->pointRowArray[rowSet]->yCoordinate = 14; 
     } 
    } 
} 


int main(void){ 
    // this was just a test for pointRow and it’s fine 
    pointRow firstRow; 
    firstRow.makePointRowArray(size); 
    firstRow.setPointRowArray(size);  

    // this works up until… 
    totalSquare firstSquare; 
    firstSquare.makeTotalSquare(size); 
    // this point. I cannot assign 25 
    // I either get a bus error 10 or segmentation fault. what am I doing wrong? 
    firstSquare.totalSquareArray[0]->pointRowArray[0]->xCoordinate = 25; 


    return 0; 
} 

我只是不知道它爲什麼它適用於pointRow,但現在totalSquare。

回答

1

您不打電話makePointRowArray您的totalSquare案件的任何地方。沒有這些,pointRowArray中的指針未初始化並可能導致程序崩潰。你可以將其添加到下面的函數可能解決這個問題:

void totalSquare::makeTotalSquare(int collumnSize){ 
    for (int i = 0; i < collumnSize; i++){ 
     totalSquareArray[i] = new pointRow; 
     totalSquareArray[i]->makePointRowArray(size); 
    } 
} 

你應該考慮在構造這樣做,這樣你就不會忘記你的使用對象時初始化數據。

+0

會做出和使用一個構造函數。非常感謝。 – 1N5818 2014-09-26 04:07:44