Why is the result of using `int (* p) [5]` so confusing?

I know that int (*p)[5] means a pointer that points to an array of 5 integers. Therefore, I program this program below:

 #include <iostream> using namespace std; int main() { int a[5]={0,1,2,3,4}; int (*q)[5]=&a; cout<<a<<endl; cout<<q<<endl; cout<<*q<<endl; cout<<**q<<endl; return 0; } 

On my machine, the result is:

 0xbfad3608 0xbfad3608 //?__? 0xbfad3608 0 

I understand that *q means that the address a[0] and **q means the value of a[0] , but why does q have the same meaning as a and *q ? In my poor mind, this should be their address! I am completely confused. Someone please help me. You are welcome!

+4
source share
3 answers

Look at it like this:

  q == &a *q == a **q == *a 

You have not tried typing &a . If you do this, you will see that it has the same meaning as a . Since &a == a and q == &a , and *q == a , transitivity q == *q .

If you want to know why &a == a , check Why is the address of the array variable the same as itself?

+8
source

q and &a are pointers to an array.

*q and a are an "array". But you cannot pass an array to a function (and std::ostream::operator<< is a function); you really pass a pointer to the first element that is created implicitly (called pointer decomposition). Thus, *q and a become pointers to the first element of the array.

The beginning of the array is in the same place in memory as the array is trivial. Since none of the pointers is a-to-char pointer (which is handled specifically to make string literals work as expected), the addresses are simply printed.

+2
source

This is because array automatically converted to pointer , which has only the value of the address of array . Therefore, when you try to print an array using <<a or <<*q , you are actually printing your address.

+1
source

Source: https://habr.com/ru/post/1383815/


All Articles