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;
}
0

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Actually I didn't get your point.You mean &p shows the address of the pointer itself?
but thats not the case with s array. &s and s return the same address. Why is that?
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
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: 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 which you might find interesting.
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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.