An array name as a constant pointer to the first element of the array Please explain

Thread Starter

integral

Joined Aug 19, 2010
22
The book I am studying from makes the following two statements:

1. The array name (without a subscript) is a (constant) pointer to the first element of the array.

2. The name of an array is actually the address in memory of the first element of the array.

When I run the following program:
Rich (BB code):
#include <iostream>
using namespace std;

int main()
{
    int b[5] = {11, 22, 33, 44, 55};
    const int *bPtr =  b;

    //Part 1
    cout << "Part 1" << endl;
    cout << "b  = " << b << endl;
    cout << "&b = " << &b << endl;
    cout << "*b = " << *b << endl;

    cout << endl;


    //Part 2
    cout << "Part 2" << endl;
    cout << "bPtr  = " << bPtr << endl;
    cout << "&bPtr = " << &bPtr << endl;
    cout << "*bPtr = " << *bPtr << endl;

    return 0;
}
I get the following result:

Rich (BB code):
Part 1
b  = 0023FEAC
&b = 0023FEAC
*b = 11

Part 2
bPtr  = 0023FEAC
&bPtr = 0023FEA8
*bPtr = 11
Press any key to continue . . .
I don't understand why the lines in red above produce the same output. I understand why b = 0023FEAC but why does &b = 0023FEAC ? If my understanding of pointers is correct, it seems like it is a pointer pointing to itself.
 

someonesdad

Joined Jul 7, 2009
1,583
First of all, integral, this is an excellent post -- I wish all the people who had questions gave code properly indented like you did, added the highlighting, and showed the output. It's quite refreshing from the manifold poorly-phrased and poorly-presented questions one often sees here. Many posters aren't smart enough to realize they're asking for a favor, so they should minimize the amount of work the reader has to do.

I recommend you use Stroustrup's C++ book for such questions (rather than e.g. K&R); I'm using 3rd ed. On page 91 is the statement "The name of an array can be used as a pointer to its initial element". Then the example following shows that, semantically, the array's name can be used as a pointer and Stroustrup mentions an implicit conversion. This is a subtle point. Note the statement is that the array's name can be used as a pointer -- that does not mean it is a pointer.

Thus, your line "cout << b" does an implicit conversion to a pointer, which then prints as the usual hex value. Here's some code:

int a[3] = {0, 1, 2};
int *p = a; // Implicit conversion to pointer

The following three lines are semantically equivalent:

int *p = a;
int *p = &a;
int *p = &a[0];

However, I believe no implicit conversion would need to be generated for the last two lines (look at the assembly to be sure).

Thus, semantically, a, &a, and &a[0] behave the same way. That's why you get the same address in the printouts. a is an array, but &a and &a[0] are addresses -- two entirely different things.
 
Top