Home > Software design >  What is the type of a 2D array of pointers, and how can it be stored?
What is the type of a 2D array of pointers, and how can it be stored?

Time:03-13

If I have a table of int pointers, ie int *arr[3][3]

Is it possible to store this in a pointer, while still retaining the array information?

While regular assignment (int ***p = arr) throws an incompatible pointer error, it is possible to cast int ***p = (int***)arr. However, accesses to the information via *arr[1][2] will not return the correct data

CodePudding user response:

When arr, having been declared as int *arr[3][3] is used in an expression other than as the operand of sizeof or unary &, it is automatically converted to a pointer to its first element. The type of that pointer is int *(*)[3].

So int *(*p)[3]; will declare a pointer of that type, after which you can assign p = arr and use p to access array elements as if it were arr.

CodePudding user response:

If you have an int *arr[3][3]; and you'd like a pointer to that, then I suggest:

int *(*parr)[3][3] = &arr;

Dereferencing it will bring the full type back with all the support you'd expect from the compiler:

(*parr)[2][2] = something;
  • Related