Thursday, February 17, 2022

[SOLVED] the meaning of '&' in C when using with array

Issue

I am learning pointer right now, and '&' operator is messing my mind in terms of datatype, especially when it's used with array.

I see that '&' operator is giving me the first memory address of whatever it is used with.

But I can't understand why this is changing the datatype when I use it with array's name. Is this just the way it is? Or are there any reasons that I don't know yet?

so, my question is,

  1. why do the datatype of array1 and array 2 is different even though they are just the name of array?
  2. why does the datatype changes just because I added '&'?
int array1[5];

int *p1 = array1;    //why does this works
int *p2 = &array1;   //but not this one?

the gcc says that one on the top right is 'int*' but one with '&' is 'int(*)[5]'.

int array2[5][5];

int (*q1)[5] = array2;    //why does this wokrs
int (*q2)[5] = &array2;   //but not this one?

the gcc says that one on the top right is 'int( * )[5]' but one with '&' is 'int( * )[5][5]'.


Solution

In C, array name gets converted to a pointer to the first element of the array. So you do not need to use '&' to get the address. When you do this, what you are getting is a pointer to an array.

See also Pointer to Array in C



Answered By - Greg
Answer Checked By - Terry (WPSolving Volunteer)