问题描述
int main(int argc,char *argv[]) {
int x[3] = {1,2,3}; //create an array x
int *y = x; //create pointer y and let it point to the array x
*y = null; //Now x points to the null,therefore x is a dangling pointer
}
这里有点困惑,既然x指向的值为null,那么x是悬空指针吗?
解决方法
x
是一个数组,声明为
int x[3] = {1,2,3};
所以它不能是一个悬空指针。数组类型的对象不是指针。
在本声明中
int *y = x;
用作初始化表达式的数组指示符 x
被隐式转换为指向其第一个元素的指针,并且该指针不是左值。在此声明之后,初始化表达式将不存在。
所以在呈现的程序中没有悬空指针。
注意这个声明
*y = null;
无效。你的意思是
y = NULL;
现在变量 y
是一个空指针。
这是一个悬空指针的例子。
int *p = malloc( sizeof( *p ) );
free( p );
在调用 free
之后,指针 p
是一个悬空指针。它没有指向有效的对象。