1

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

  • *However, accesses to the information via `*arr[1][2]` will not return the correct data* That's because an `int ***` has nothing to do with referring to a "2D array of pointers" despite what you may have been told. The closest an `int ***` can come is a pointer to a 1D array of multiple, separate 1D arrays of pointers to `int *`. And that's not a 2D array. Arrays are not pointers and pointers are not arrays. Arrays in some cases [decay to a pointer to their first element](https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-decay). – Andrew Henle Mar 13 '22 at 00:45

2 Answers2

2

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.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
2

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;
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108