C 打印空指针时会显示“空”&引用;分段故障(堆芯转储)

C 打印空指针时会显示“空”&引用;分段故障(堆芯转储),c,pointers,C,Pointers,我正在尝试探索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: %

我正在尝试探索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;

}
#包括
int main(){
无符号int*ip=NULL;
printf(“存储在指针中的地址:%x\n”,ip);//给出0
printf(“存储在指针中存储的地址处的值:%d\n”,*ip);//给出“分段错误(核心转储)”
返回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");

可能重复为什么你说“它应该输出一个值”?你在哪里读到的?因为你读到的是错误的。这就是为什么将指针设置为NULL是一个好的实践。因此,如果你取消引用它,就会得到一个错误。使用%p打印指针。
*ip
取消对空指针的引用,这通常会导致现代系统(MacOS、Windows、Linux)崩溃。感谢大家分享您的见解……我还查看了@2501的链接。感谢@GingerPlusPlus为新手提供更清晰的解释:)