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

I read this question on stackoverflow C pointer to array / array of pointer values

I stumbled upon The int (*q)[3]; // q is a pointer to array of size of 3 integers

discussion was quite clear for understanding complex declarations in C.

I can't figure out when it is used and how is it used? how am i playing it? can anyone please explain me some code examples like initialize a pointer and dereference 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 following the above instructions, I realized that q can point to an array of size n row but 3 column

. How do I dereference these values?

 printf("%d",*q); gives some strange value 229352.

      

Can anyone explain to me how to initialize and how to play pointers and its memory layout?

+3


source to share


1 answer


Since it q

can point to an array, you should

  • put its value into the address of the array: q = &c;

    and
  • Seek it to get the array: ++(*q)[1]

    , printf("%d", (*q)[2])

    etc.

Note that strings b

are also type arrays int[3]

, so you can assign the q

address of each string as well b

:



q = b + 0;    // (*q)[i] == b[0][i]
q = b + 1;    // (*q)[i] == b[1][i]

      

(In contrast, strings d

are of type int[5]

, so their addresses are not type-compatible q

, and of course, the address is a

also incompatible, since the type is if a

int

.)

+2


source







All Articles