5
int main(){
    int a[4] = { 1,2,3,4 };
    int(*b)[4] = &a; //with a doesn't work
    cout << a << &a  << endl; //the same address is displayed
}

So, int(*b)[4] is a pointer to an array of ints. I tried to initialize it with &aand a both. It works only with the first.
Aren't they both addresses of the first element of the array?

5
  • You mean "initialize", not "instantiate" Commented Jul 20, 2017 at 2:52
  • Pointers have a type; (i.e. they're an address and a type). This doesn't work for the same reason that int x; double *p = &x; doesn't work. Commented Jul 20, 2017 at 2:54
  • @P. Danielski: How would you differentiate between "address of the first element of the array" and "address of the entire array" if both begin at the same point in memory? A similar example: struct S { int x; } s;. Then &s and &s.x are the same numerical address. So, what is &s then: adress of the entire struct object or address of its first field? Commented Jul 20, 2017 at 2:57
  • Possible duplicate of Pointer to an array of ints Commented Jul 20, 2017 at 6:43
  • Is &a[0] the same as (char*)&a[0]? Commented Jul 21, 2017 at 2:51

2 Answers 2

7

Conceptually they're not the same thing. Even they point to the same address, they're incompatible pointer types, thus their usages are different either.

&a is taking the address of an array with type int [4]), then it means a pointer to array (i.e. int (*)[4]).

a causes array-to-pointer decay here, then it means a pointer to int (i.e. int*).

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

Comments

0

Take a look at this piece of code

int a[4] = { 1, 2, 3, 4 } // array 
int(*b) = a // pointer to the first element of the array

You should know that int(*b) is equal to int(*b)[0] and a[0]. Therefore, It's a pointer pointing to an integer(int*), not a pointer pointing to an array of integer.

That how type issue arises in your case.

Noted that C is a strong type language. Look at your assignment statement.

int(*b)[4] = &a;

It takes a parameter of int(*ptr)[4]. It means you have to strictly pass the argument of that type, which is a int *.

And you are trying to pass a pointer to array of 4 int to int * . Therefore, they're not compatible in the assignment, even their address are the same.

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.