分配两个维数组

时间:2018-03-06 09:28:32

标签: c++ arrays

我有以下C ++节点

unsigned int uiNoOfItems = 113;
unsigned int W = 2347;

// create two dimensional array

unsigned int ** optimalWeight = new unsigned int* [uiNoOfItems + 1];
for (unsigned int uiRowIdx = 0; uiRowIdx <= uiNoOfItems; uiRowIdx++) {
    optimalWeight[uiRowIdx] = new unsigned int (W + 1);
}


std::cout << " initializing first column "<< std::endl;
// initialize first column
for (unsigned int uiRowIdx = 0; uiRowIdx <= uiNoOfItems; uiRowIdx++) {
    optimalWeight[uiRowIdx][0] = 0;
}

std::cout << " initializing first row "<< std::endl;
// initialize first row
for (unsigned int uiColIdx = 0; uiColIdx <= W; uiColIdx++) {
    // std::cout << uiColIdx << std::endl;
    optimalWeight[0][uiColIdx] = 0; ------------------------> crash happens here at uiColIdx value 1210
}

上面的代码崩溃发生在上述行。我不知道为什么内存分配是成功的。

1 个答案:

答案 0 :(得分:1)

你也可以这样做

unsigned const int uiNoOfItems = 113;
unsigned const int W = 2347;    

int (*var)[W] = new int[uiNoOfItems][W];