4

Is there an easy way to convert an instance of type int[n][n] to int**? For example, the code

void foo(int** arr) {
// ...
}
int X[10][10];
memset(X,0,10*10*sizeof(int));
foo(X); // error: cannot initialize a parameter of type 'int **' with an lvalue of type 'int [10][10]'

An easy workaround is, of course, to have

int** X=new int*[10];
for (int i=0;i<10;++i) X[i]=new int[10];

but this somewhat counters the idea that in C++ arrays are just pointers (which the 1-dim arrays certainly are).

r0fg1
  • 157
  • 1
  • 8

1 Answers1

3

Nope. An int[N][M] under the hood is a contiguous block of memory (where the extra dimensions are flattened) with some syntax sugar to make the compiler do the math to access the elements.

An int ** (actually int *[N]) is a completely different beast, since it uses an extra later of indirection that allows each row to reside elsewhere; heck, you may even have NULL rows or rows of different length.

OTOH if you have a "true" multidimensional array and need an int ** you can bridge the gap by creating only the "pointer index", and making it point inside the original array.

int *a[10];
for(int i=0; i<10; ++i) 
    a[i]=arr[i];
Matteo Italia
  • 123,740
  • 17
  • 206
  • 299