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 code, is a a pointer to itself?
#include<stdio.h>
int main(){
int* a;
int b = (int)&a;
a = b;
printf("address of a = %d\n", &a);
printf(" value of a = %d\n", a);
}
If a is not a pointer to itself, then the same question poses again: Can a pointer point to itself?
Also, how is a self pointing pointer useful?
What you’re actually doing there is not having the pointer point to itself. You are using the memory space allocated for the pointer to store the location of the pointer. A pointer to an int points to ints – never to other pointers to ints, including itself.
For example, let’s say you create a pointer
a:It gets its own spot in memory:
In this simple example, let’s say a is at memory location ‘5’.
If you were to do this:
…the following would happen:
What’s happening here is that
ais pointing to what it thinks is an integer at location 5. This also happens to be the same memory location that&ais pointing to, but in the context of whatais pointing to, it’s now pointing to the integer at location 5 – and that integer is 5.For example both of these would work:
If you wanted to create a pointer to a, you most definitely could – either of these ways:
or
But it’s very important to realize that
aisn’t a pointer to itself. It’s a pointer to the integer at the location it stores – which just happens to be the same as its own location.To further show (through an even simpler example) what’s going on, something similar could happen with an
int. That is, you can store the memory location of anintwithin itself:anow has a location in memory, and has a value of 999 (we’ll pretend it’s been placed in the memory location ’46’):It’s in the location ’46’ – if we wanted, we could store this number as an integer within
a:and now
ais equal to&ain value, but not in type –ais just an integer, it doesn’t point to itself magically now just because we used it to store its own memory location.