0

I'm trying to make a dynamic 2-dimensional array.

Here is my code:

bool b_alloc_table_2_dim(int ***piTable, int iSizeX, int iSizeY)
{
    *piTable = new int*[iSizeX];
    for (int ii = 0; ii < iSizeX; ii++)
        *piTable[ii] = new int[iSizeY]; // here i get the exception
    return true;
}

int main()
{
    int **x ;
    b_alloc_table_2_dim( &x, 3, 5);

    return 0;
}

I can't find anything wrong with the code. After calling my function x is supposed to point to the 2d array.

genpfault
  • 51,148
  • 11
  • 85
  • 139
  • 2
    `0xcccccccc` should be recognized as uninitialized stack memory [https://stackoverflow.com/questions/127386/in-visual-studio-c-what-are-the-memory-allocation-representations/127404#127404](https://stackoverflow.com/questions/127386/in-visual-studio-c-what-are-the-memory-allocation-representations/127404#127404) – drescherjm Oct 14 '19 at 18:55
  • 1
    [See this as to why your general approach is flawed](https://stackoverflow.com/questions/21943621/how-to-create-a-contiguous-2d-array-in-c/21944048#21944048). – PaulMcKenzie Oct 14 '19 at 18:58
  • 1
    You should use an actual container if you are writing c++. Are you writing c or c++ ? – darune Oct 14 '19 at 19:12

2 Answers2

3

The [] operator takes precedence over *. cppreference

So the line

*piTable[ii] = new int[iSizeY];

is equivalent to

*(piTable[ii]) = new int[iSizeY];

what you wanted to write is:

(*piTable)[ii] = new int[iSizeY];
luantkow
  • 2,809
  • 20
  • 14
0

Use an actual container

Using an actual container avoids a lot of the types of issues that you have encountered.

Instead of

int**

For a 2d array (a matrix) a more suitable data structure could be

std::array< std::array<int, cols>, rows> 

if the sizes is known at compile time.


If not, it's probably best to just use a single vector ala.

auto my_array2d = std::vector<int>(rows*cols);//array now has 'rows*cols' elements of '0'

and handle indexing yourself.

The best thing is of course to use a library like perhaps or

darune
  • 10,480
  • 2
  • 24
  • 62