写入二维向量时访问冲突

时间:2016-06-26 06:45:40

标签: c++ multidimensional-array vector

我的程序在x = 2y = 6 cellChargeTime[x][y].push_back(0);时一直在崩溃。有关如何解决此问题或导致此次崩溃的原因的任何想法。

vector<int> **cellChargeTime;

cellChargeTime = new vector<int>*[xMax]; //xMax = 40
for (int x=0; x<xMax; x++)
    cellChargeTime[x] = new vector<int> [yMax]; //yMax = 40

for (int x=0; x<xMax; x++){
    for (int y=0; y<yMax; y++){
        for (int i=0; i< numRuns; i++){ //numRuns = 1
            cellChargeTime[x][y].push_back(0); // Crashes at x = 2; y = 6
        }
    }
}

1 个答案:

答案 0 :(得分:0)

如图所示,代码没有问题,它工作正常(假设您在使用delete[]完成后有足够的cellChargeTime语句。)

但是,我建议采用不同的内存管理方法:

vector<vector<int> > cellChargeTime;

cellChargeTime.resize(xMax);
for (int x=0; x<xMax; x++)
    cellChargeTime[x].resize(yMax);

填充向量的循环根本不会改变:

for (int x=0; x<xMax; x++){
    for (int y=0; y<yMax; y++){
        for (int i=0; i< numRuns; i++){ //numRuns = 1
            cellChargeTime[x][y].push_back(0);
        }
    }
}