Is it possible to initialize a C pointer to NULL?
是的,非常喜欢.
The actual claim made on the guide reads like
On the other hand, if you use just the single initial assignment, 100, the program will try to fill the contents of the memory location pointed to by 101 with the value 2. Since 101 is filled with garbage, it can be any address. [...]
他们错了,你是对的.
对于声明,(ignoring, for now, the fact that pointer to integer conversion is an implementation-defined behaviour)
int * my_int_ptr = 2;
my_int_ptr
是一个变量(指向int
的指针类型),它有自己的地址(类型:指向整数的指针的地址),您正在将值2
存储到that地址中.
现在,my_int_ptr
,作为一个指针类型,我们可以说,它points to存储位置pointed by处的"type"的值,也就是保存在my_int_ptr
中的值.因此,您实质上是将指针变量赋给值of,而不是指针所指向的内存位置的值.
所以,作为结论
char *x=NULL;
将指针变量x
初始化为NULL
,而不是value at the memory address pointed to by the pointer.
这是same as
char *x;
x = NULL;
Expansion:
现在,在严格遵守的情况下,像这样的声明
int * my_int_ptr = 2;
是非法的,因为它涉及到违反约束.我要说清楚的是,
my_int_ptr
是指针变量,类型为int *
- 根据定义,整型常量
2
的类型为int
.
而且它们不是"兼容"类型,所以这个初始化是无效的,因为它违反了在第Lundin's answer章§6.5.16.1/P1中提到的简单赋值规则.
如果有人对初始化如何与简单赋值约束相关联感兴趣,请引用第11页第6.7.9章第C11
条
标量的初始值设定项应为单个表达式,可以 Select 用大括号括起来.这个