c - 打印空指针给出 ""段错误(核心已转储)

标签 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: %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/

相关文章:

c - 了解指针的用途

困惑 : Dynamic Allocation of 2D array, C

c - TRF7970 : Mifare Classic authentication

c - 指针的自增和加法

c - 初始化指针到指针而不丢失保留内存

C 指向 Swift 指针的指针

c - 比较相等的两个指针是否转换为整数类型比较相等?

c - 使用 char 将大数相加并返回值。指针错误

C-函数隐式声明时间,rand,printf,我所有的函数调用

c - 如何在 C 中实现位集