-3

I have following C++ node

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
}

Above code crash is happening at mentioned line. I am not getting why as memory allocation is successfull.

Nadun Kulatunge
  • 1,567
  • 2
  • 20
  • 28
venkysmarty
  • 11,099
  • 25
  • 101
  • 184
  • 6
    `new unsigned int (W + 1);` Does **not** create an array of `W + 1` size. Did you mean to write `new unsigned int [W + 1];`? – Algirdas Preidžius Mar 06 '18 at 09:30
  • Thanks for pointing it out. Silly mistake . – venkysmarty Mar 06 '18 at 09:31
  • 1
    why the stl-tag when you actually aren't using containers? – The Techel Mar 06 '18 at 09:38
  • These pointer-to-pointer things are not 2D arrays. See [Correctly allocating multi-dimensional arrays](https://stackoverflow.com/questions/42094465/correctly-allocating-multi-dimensional-arrays) - replace malloc with new and free with delete[] and you get C++. Though of course, preferably use a C++ container class instead. – Lundin Mar 06 '18 at 09:50

1 Answers1

1

You can do it in this way as well

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

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