分段错误与类指针数组的另一个类的指针数组

时间:2014-09-26 03:16:01

标签: c++ class pointers object segmentation-fault

我没有得到任何编译错误,也没有在尝试仅使用另一个类的一个类指针数组执行此操作时出现任何错误。当我用三个班级做的时候。我崩溃了

#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 个答案:

答案 0 :(得分:1)

您未在makePointRowArray案例中的任何地方致电totalSquare。没有它,pointRowArray中的指针未初始化,可能会导致程序崩溃。您可以通过将其添加到以下函数来解决此问题:

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

您应该考虑在构造函数中执行此操作,以便在使用对象时不要忘记初始化数据。