Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I know that int (*p)[5] means a pointer which points to an array of 5 ints. So I code 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 can understand that *q means the address of a[0] and **q means the value of a[0], but why does q have the same value as a and *q? In my poor mind, it should be the address of them! I'm totally confused. Somebody please help me. Please!

like image 687
Archeosudoerus Avatar asked Dec 21 '22 05:12

Archeosudoerus


1 Answers

Look at it this way:

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

You didn't try printing &a. If you do, you'll see that it has the same value as a. Since &a == a, and q == &a, and *q == a, by transitivity q == *q.

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

like image 126
rob mayoff Avatar answered Dec 24 '22 01:12

rob mayoff