我正在尝试探索 C 中的指针,对于这个主题来说还很陌生。我开始知道最佳实践是在声明指针时分配“NULL”。所以在下面的程序中我做了同样的事情:
#include <stdio.h>
int main() {
unsigned int *ip = NULL;
printf("Address stored in pointer: %x \n",ip); //gives 0
printf("Value stored at Address stored in pointer: %d \n",*ip); // gives "Segmentation fault (core dumped)"
return 0;
}
我无法清楚地理解为什么会发生这种情况。它不应该输出一个值(NULL 或其他值)。
我使用的是centos 6.5和gcc版本4.4.7。
最佳答案
人们将NULL
分配给指针以表明它不指向任何内容。
取消引用指向不属于您的程序的内存的指针
(NULL==0
,地址0
属于您的操作系统)
是未定义的行为。
人们将NULL
分配给指针以便能够写入
if(ip) //NULL==0==false, so the condition means "if ip points to something"
printf("Value stored at Address stored in pointer: %d \n",*ip);
else printf("The pointer points to NULL, it can't be dereferenced\n");
关于c - 打印空指针给出 ""段错误(核心已转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26362340/