4

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!

4

3 回答 3

8

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?

于 2011-11-30T08:16:48.520 回答
2

q and &a are pointers to the array.

*q and a are "the array". But you can't really pass an array to a function (and std::ostream::operator<< is a function); you really pass a pointer to the first element, which is created implicitly (called pointer decay). So *q and a become pointers to the first element of the array.

The beginning of the array is at the same location in memory that the array is, trivially. Since none of the pointers involved are pointers-to-char (which are handled specially so that string literals will work as expected), the addresses just get printed out.

于 2011-11-30T09:13:49.233 回答
1

That because array is automatically converted to a pointer, which just has the value of the address of the array. So when you are trying to print print the array using <<a or <<*q, you are in fact printing its address.

于 2011-11-30T08:18:56.093 回答