Can a pointer ever point to itself?

前端 未结 8 910
情深已故
情深已故 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条回答
  •  猫巷女王i
    2020-12-04 16:14

    Well, first I'd change the code around:

    int **a;
    a = (int **)&a;  // otherwise you get a warning, since &a is int ***
    

    I'm not sure why you would do this, but it is allowed.

    printf("The address of a is %p\n", &a);
    printf("a holds the address %p\n", a);
    printf("The value at %p is %p\n", a, *a); // the *a is why we made a an int **
    

    They should print out the same thing.

    The address of a is 0x7fffe211d078
    a holds the address 0x7fffe211d078
    The value at 0x7fffe211d078 is 0x7fffe211d078
    

    Note that this is not a good idea, as that very first cast a = (int **)&a is a hack to force a to hold a value that it shouldn't hold. You declare it an int ** but try to force an int *** into it. Technically the sizes are the same, but in general don't do that because people expect that an int * holds the address of something that can be used as an int, an so on.

提交回复
热议问题