Can a pointer ever point to itself?

前端 未结 8 884
情深已故
情深已故 2020-12-04 15:29

My question is: If a pointer variable has the same address as its value, is it really pointing to itself?

For example - in the following piece of c

相关标签:
8条回答
  • 2020-12-04 16:24

    Just:

    int *a = (int*)&a;
    cout<<"checking: \n"<<&a<<"\n"<<a;
    

    It points to itself.

    0 讨论(0)
  • 2020-12-04 16:25

    Yes and no, because the pointer's type is almost as important as the pointer's value.

    Yes, a pointer can contain the position of a pointer to itself; even a long can contain the position of a pointer to itself. (Ints usually can, but I don't know if that's guaranteed everywhere.)

    However, there is no type to represent this relationship. If you have a pointer which points to itself, you actually have a different type when you dereference it. So:

    void *p = &p;
    // *p is illegal, even though you probably wanted it to equal 'p'
    if( *p != p ) {
        printf("Something's wrong");
    }
    
    int *i = (int*)&i;
    // The following statement is still illegal
    if( *i == i ) {
        printf("The universe works!");
    }
    

    I would say the answer is 'no', because it won't work unless you're going to abuse the type system. I think it's an indication that you're doing something wrong (though sometimes it's certainly necessary).

    0 讨论(0)
提交回复
热议问题