Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

c - Can a pointer ever point to itself?

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
", &a);
   printf("  value of a = %d
", 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...