3

I was just playing with pointers and found this weird thing. I created the pointer p and displayed its address as I did in the following program, the address of p and &p is different, why are they different?

int main()
{
    int *p, s[5];
    cout << p <<endl;
    cout << &p <<endl;
    p = s;
    cout << p <<endl;
    cout << &p <<endl;
}
Matt
  • 22,721
  • 17
  • 71
  • 112
Umer Farooq
  • 7,356
  • 7
  • 42
  • 67

3 Answers3

3

P is a pointer that means it holds an address to an integer. So when you print p it displays address of the integer it points to. Whereas when you print &p you are actually printing the address of p itself rather than the address it points to.

Jeeva
  • 4,585
  • 2
  • 32
  • 56
  • 1
    Actually I didn't get your point.You mean &p shows the address of the pointer itself? – Umer Farooq Jul 12 '12 at 06:07
  • but thats not the case with s array. &s and s return the same address. Why is that? – Umer Farooq Jul 12 '12 at 06:14
  • 1
    thats because s is not an pointer it is an array. When you say 's' it points to the base address of the array which is same as saying &s – Jeeva Jul 12 '12 at 06:17
  • man I am kind of forgetting all this. I was master in these things but its been a while I have been untouch with C++ – Umer Farooq Jul 12 '12 at 06:18
  • 1
    @Umer: If `s` is an array, say, of type `int[10]`, and you try to print it, it will silently convert to a pointer to its first element, which is of type `int*`. The type of `&p`, on the other hand, is `int(*)[10]`. As you can see from the type, `&p` points to the *entire* array, not just the first element. But since an array and its first element start at the same address in memory, you get the same output. We have a [related FAQ](http://stackoverflow.com/questions/4810664/) which you might find interesting. – fredoverflow Jul 12 '12 at 06:34
1

As Jeeva said, pointer p also occupies a part of memory(the yellow part in this pic, its address is 0x300) and in this area, it holds the value which is the address of the array s. So p == 0x100 and &p == 0x300Pointer

tmj
  • 1,143
  • 3
  • 11
  • 15
1

If p were equal to &p, the pointer would point to itself, which is only possible with void pointers:

void* p = &p;
assert(p == &p);

I have yet to see a practical use for this, though :)


Oh wait, it also happens in self-referencing recursive data structures, which can be quite useful:

struct X
{
    X* p;

    void print()
    {
        std::cout << " p = " <<  p << '\n';
        std::cout << "&p = " << &p << '\n';
    }
};

X x;
x.p = &x;
x.print();

Think linked container, where the last node has itself as its successor. Output on my system:

 p = 0x7fffb4455d40
&p = 0x7fffb4455d40

Why? Because an object usually starts at the same address in memory as its first data member.

fredoverflow
  • 256,549
  • 94
  • 388
  • 662