3

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?

Community
  • 1
  • 1
user3205479
  • 1,443
  • 1
  • 17
  • 41

1 Answers1

2

Since q can point to an array, you have to

  • make its value the address of an array: q = &c;, and
  • dereference it to get an array: ++(*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.)

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • Thanks, but q = c; is valid case I guess. arrays are replaced with their addresses, q = c and q =&c[0] are both same? right – user3205479 Oct 09 '14 at 09:46
  • @user3205479: The address is just one part of object identity. The *type* is another one. The address of the array is `&c`, that's it. What you call `c` is the address of the first element of the array, which is something different. – Kerrek SB Oct 09 '14 at 09:54