简体   繁体   中英

Pointer and array address

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

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.

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 == 0x300 指针

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM