Reputation: 57
I was wondering if it is possible to dereference a pointer to a two dimensional array in C:
int matrix1[2][2] = {{1,2},{3,4}};
int matrix2[2][2] = {{4,5},{6,7}};
I am trying to create an array of pointers, where the first pointer points to matrix1 and the second one to matrix2. I thought of
int *(pt[2]);
pt[0] = &matrix1
My goal would be to be able to access any element in one of the two array with something like:
pt[0][n][m];
Or for the second matrix:
pt[1][n][m]
But as far as I know this doesn't work. Is the pointer declaration wrong?
Upvotes: 3
Views: 900
Reputation: 780
The answer provided is correct but lacks explanation. I think it is more helpful if you understand why your approach failed.
Using array indexes on pointers works by incrementing the pointer using the size of the data type.
For example if we define an array as follows:
int a[2] = {1,2};
and assume that the array was created in memory at location x
a[0]; // points at x
a[1]; //points at x + sizeof(int)
now lets take the example of two dimensional array
int a[2][2] = {{1,2},{3,4}}
again assume location x
a[0]; //points at x
a[1]; //points at x + sizeof(int [2]) because int[2] is the data type
a[0][1]; // points at x + sizeof(int)
a[1][1]; // points at x + sizeof(int[2]) + sizeof(int)
Now lets take your example
int matrix1[2][2] = {{1,2},{3,4}};
int matrix2[2][2] = {{4,5},{6,7}};
int *pt[2];
pt[0] = &matrix1; //doesn't compile
First, that won't really compile because the type of pt is pointer to int and matrix1 is a pointer to int[2]. However, you can force it by casting like this
pt[0] = (int*)&matrix1;
But it still won't work because the following is not valid either
pt[0][n][m]; //fails to compile
This is because pt is an array of pointer to int, so pt[0][n] points at an integer, not an array. As such you cannot use apply an index to it
However, if you define it as follows
int (*pt[2])[2] = {&matrix1,&matrix2}
pt is then an array of pointers to two dimensional arrays. As such, assuming matrix1 defined at x1 and matrix2 defined at x2,
pt[1][1][1]; //points to x2 + sizeof(int[2]) + sizeof(int)
Upvotes: 0