分配二维数组[关闭]

问题描述 投票:-3回答:1

我有以下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
}

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

c++ arrays
1个回答
1
投票

你也可以这样做

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

int (*var)[W] = new int[uiNoOfItems][W];
© www.soinside.com 2019 - 2024. All rights reserved.