You can construct a self referencing pointer this way:
void *p = &p;
p
is a generic pointer that points to itself.
The problem is you cannot dereference this pointer without a cast to an actual pointer type. Here is code to demonstrate this:
#include <stdio.h>
int main() {
void *p = &p;
printf("p = %p\n", p);
printf("*(void **)p = %p\n", *(void **)p);
printf("*(void **)p %c= p\n", *(void **)p == p ? '=' : '!');
return 0;
}
As commented by Jonathan Leffler, void *p; p = &p;
features a type conversion, but any data pointer type can be converted to void *
without a cast. The type of &p
is void **
, but the implicit conversion to void *
is permitted by C.
There are also self referring types:
struct self { struct self *self; };
This structure is not very useful, it is a simple indirection, but you can initialize it in a self referring way:
#include <stdio.h>
struct self { struct self *self; };
int main() {
struct self s = { &s };
struct self *p = &s;
printf("p = %p\n", (void *)p);
printf("p->self = %p\n", (void *)p->self);
printf("p %c= p->self\n", p == p->self ? '=' : '!');
return 0;
}
In both cases, p
contains its own address, which can be interpreted as p
is self-referential.