Mitch Ostler
Mitch Ostler

Reputation: 73

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

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

Upvotes: 1

Views: 40

Answers (2)

Ted Lyngmo
Ted Lyngmo

Reputation: 117812

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;

Upvotes: 2

Eric Postpischil
Eric Postpischil

Reputation: 223768

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.

Upvotes: 2

Related Questions