0

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]'.

F_Schmidt
  • 902
  • 1
  • 11
  • 32
Delisle
  • 5
  • 3
  • Does this answer your question? [Why can't I treat an array like a pointer in C?](https://stackoverflow.com/questions/12676402/why-cant-i-treat-an-array-like-a-pointer-in-c) – gspr May 15 '21 at 10:52
  • 1
    The unary `&` operator gives the address of its operand. The data type of the result is pointer to whatever type that operand has. So if you have `int a`, then `&a` has type `int *`. If you have `int b[10]` then `&b` has type `int (*)[10]`. – Tom Karzes May 15 '21 at 10:53
  • See also https://stackoverflow.com/a/2094795/1524450 – Michael May 15 '21 at 10:54
  • Actually once you're creating an array, the first member of this array becomes a pointer which points to the ```array1```in your example ```int array1[5];```. So if you do this ```int *p2 = &array1;```you will be taking an address of a pointer since ```array1```is actually a pointer.. – Ali Ziya ÇEVİK May 15 '21 at 10:59

2 Answers2

1

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

Greg
  • 87
  • 11
0

Pointers in c have very deep implementation. Pointers , as name suggest pointes to a data location. Pointers in c have a datatype which tells about the data type of data.

int * ptr;

this is pointer daclaration.

int i = 30; ptr = &i ; // this returns address of variable t

in terms of array both arr, &arr return address of array

int (*p)[5] = &arr or arr , both works , otherwise send the error message with question.

hsuecu
  • 107
  • 8