Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how, where and why someone would use int (*q)[3];

Tags:

arrays

c

pointers

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?

like image 849
user3205479 Avatar asked Dec 20 '25 03:12

user3205479


1 Answers

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.)

like image 180
Kerrek SB Avatar answered Dec 21 '25 18:12

Kerrek SB