【发布时间】:2015-10-03 17:11:35
【问题描述】:
我指的是What's the difference between a null pointer and a void pointer?中的NULL指针 根据@AnT 的帖子回复,“形式上,每个特定的指针类型(int *、char * 等)都有自己专用的空指针值”
我写了一个简单的程序。但是指针值对于整数或字符不是固定的。它有时会改变。那么我们如何才能得出指向 int 的 NULL 指针具有固定值的结论呢?指针的值也永远不会是 0。
#include <stdio.h>
int main()
{
int a;
char *ptr; // Declaring a pointer without initializing it
int *ptrToInt;
if(ptr)
{
printf("Pointer is not NULL\n");
printf("Value of pointer = %x\n",ptr);
printf("Value of pointer = %x\n",ptrToInt);
}
else
{
printf("Pointer is NULL\n");
printf("Value of pointer = %x",ptr);
printf("Value of pointer = %x\n",ptrToInt);
}
return 0;
}
【问题讨论】:
-
你的
if(ptr)是未定义的行为,因为ptr是一个未初始化的自动变量。参见 C11 标准草案6.2.4 Storage durations of objects, Section 6和Annex J.2 Undefined behavior。 -
我没有看到任何空指针,只有两个未初始化的指针。
-
应该是
char *ptr = NULL; -
未初始化的指针不是空指针。
-
并且不要打印带有整数格式字符串类型说明符的指针值,而是使用正确的
"%p"!