如果指针变量与其值具有相同的地址,它是否真的指向自身? [重复]

时间:2022-03-23 23:57:56

This question already has an answer here:

这个问题在这里已有答案:

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?

如果a不是指向自身的指针,则同样的问题再次出现:指针可以指向自身吗?另外,自指向指针有用吗?

1 个解决方案

#1


1  

Your code is ill-formed, your compiler should give an error. a = b; fails: int is not implicitly convertible to int *.

您的代码格式不正确,您的编译器应该给出错误。 a = b;失败:int不能隐式转换为int *。

Supposing you fix it to say:

假设您修复它说:

int *a = (int *)&a;

then it could be said that a points at the same byte in memory where a itself is stored. However it would cause undefined behaviour to read or write through *a (strict aliasing violation).

然后可以说在存储器本身存储的相同字节处有一个点。但是,它会导致未定义的行为通过* a读取或写入(严格别名冲突)。

#1


1  

Your code is ill-formed, your compiler should give an error. a = b; fails: int is not implicitly convertible to int *.

您的代码格式不正确,您的编译器应该给出错误。 a = b;失败:int不能隐式转换为int *。

Supposing you fix it to say:

假设您修复它说:

int *a = (int *)&a;

then it could be said that a points at the same byte in memory where a itself is stored. However it would cause undefined behaviour to read or write through *a (strict aliasing violation).

然后可以说在存储器本身存储的相同字节处有一个点。但是,它会导致未定义的行为通过* a读取或写入(严格别名冲突)。