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

4
  • Does this answer your question? Why can't I treat an array like a pointer in C? Commented May 15, 2021 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]. Commented May 15, 2021 at 10:53
  • See also stackoverflow.com/a/2094795/1524450 Commented May 15, 2021 at 10:54
  • Actually once you're creating an array, the first member of this array becomes a pointer which points to the array1in your example int array1[5];. So if you do this int *p2 = &array1;you will be taking an address of a pointer since array1is actually a pointer.. Commented May 15, 2021 at 10:59

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.