Can a pointer ever point to itself?

前端 未结 8 886
情深已故
情深已故 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:06

    void* p = &p;
    

    It's not terribly useful, but structs that point to themselves are useful in circular lists of length 1:

    typedef struct A {
      struct A* next;
    } A;
    
    A a = { &a };
    

    Per your exact example, I believe you meant:

    int* a;
    int b = (int)&a;
    a = (int*)b;
    
    // which can be simplified to:
    int* a = (int*)&a;
    

提交回复
热议问题