I was reading this question on stackoverflow C pointer to array/array of pointers disambiguation
I came across int (*q)[3]; // q is a pointer to array of size of 3 integers
The discussion was quite on understanding complex declarations in C.
Iam unable to understand when it is used and how it is used? how do I dereference it? could anyone explain me with some sample codes, like initializing the pointer and dereferencing it.
int main(){
int a =45;
int c[3] = {23};
int b[2][3];
int d[2][5];
int (*q)[3];
b[0][0]=1;
b[0][1]=2;
b[0][0]=3;
q = &a; // warning incompatible pointer type
q = c; // warning incompatible pointer type
q = b; // no warnings works fine
q = d; // warning incompatible pointer type
return 0;
}
After trying the above statements, I understood q can point to an array of n row but 3 column sized array. How do I dereference those values?
printf("%d",*q); gives some strange value 229352.
Could anyone explain me how to initialize and how to dereference the pointers and its memory layout?
Since q can point to an array, you have to
q = &c;, and++(*q)[1], printf("%d", (*q)[2]), etc.Note that the rows of b are also arrays of type int[3], so you can also assign to q the address of each row of b:
q = b + 0; // (*q)[i] == b[0][i]
q = b + 1; // (*q)[i] == b[1][i]
(By contrast, the rows of d have type int[5], so their addresses are not compatible with the type of q, and of course the address of a is also not compatible, since the type if a is int.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With