在C语言中,各种零值之间似乎存在差异——NULL、NUL和0。

我知道ASCII字符“0”的值为48或0x30。

NULL指针通常定义为:

#define NULL 0

Or

#define NULL (void *)0

此外,还有NUL字符“\0”,它的值似乎也是0。

是否存在这三个值不能相等的情况?

在64位系统上也是这样吗?


当前回答

这三者在不同的上下文中定义了0的含义。

指针上下文-使用NULL,表示指针的值为0,与它是32位还是64位无关(一种情况是4字节,另一种情况是8字节的零)。 string context -表示数字0的字符的十六进制值为0x30,而NUL字符的十六进制值为0x00(用于终止字符串)。

当你查看内存时,这三个总是不同的:

NULL - 0x00000000 or 0x00000000'00000000 (32 vs 64 bit)
NUL - 0x00 or 0x0000 (ascii vs 2byte unicode)
'0' - 0x20

我希望这能解释清楚。

其他回答

“NUL”不是0,而是指ASCII的NUL字符。至少,我看到它是这样使用的。空指针通常定义为0,但这取决于您正在运行的环境,以及您正在使用的操作系统或语言的规范。

在ANSI C中,空指针被指定为整数值0。所以任何不符合标准的世界都是不符合ANSI C的。

似乎很多人误解了NULL、'\0'和0之间的区别。为了避免重复之前说过的话,我来解释一下:

int类型的值为0的常量表达式,或该类型的表达式,转换为void *类型是空指针常量,如果转换为指针则成为空指针。该标准保证与指向任何对象或函数的任何指针的比较不相等。

NULL是一个宏,定义为空指针常量。

\0是一个用于表示空字符的结构,用于结束字符串。

空字符是一个所有位都设置为0的字节。

一篇帮助我开始学习C语言的好文章(摘自Linden的Expert C Programming)

一个l为空,两个l为空

记住这个小押韵来回忆指针和ASCII零的正确术语:

The one "l" NUL ends an ASCII string,

The two "l" NULL points to no thing.

Apologies to Ogden Nash, but the three "l" nulll means check your spelling. 

位模式为0的ASCII字符称为“NUL”。 特殊的指针值意味着指针不指向任何地方是“NULL”。 这两个词在意思上是不可互换的。

这三者在不同的上下文中定义了0的含义。

指针上下文-使用NULL,表示指针的值为0,与它是32位还是64位无关(一种情况是4字节,另一种情况是8字节的零)。 string context -表示数字0的字符的十六进制值为0x30,而NUL字符的十六进制值为0x00(用于终止字符串)。

当你查看内存时,这三个总是不同的:

NULL - 0x00000000 or 0x00000000'00000000 (32 vs 64 bit)
NUL - 0x00 or 0x0000 (ascii vs 2byte unicode)
'0' - 0x20

我希望这能解释清楚。

如果NULL和0是等价的空指针常数,我应该使用哪个?在C常见问题解答列表中也解决了这个问题:

C programmers must understand that NULL and 0 are interchangeable in pointer contexts, and that an uncast 0 is perfectly acceptable. Any usage of NULL (as opposed to 0) should be considered a gentle reminder that a pointer is involved; programmers should not depend on it (either for their own understanding or the compiler's) for distinguishing pointer 0's from integer 0's. It is only in pointer contexts that NULL and 0 are equivalent. NULL should not be used when another kind of 0 is required, even though it might work, because doing so sends the wrong stylistic message. (Furthermore, ANSI allows the definition of NULL to be ((void *)0), which will not work at all in non-pointer contexts.) In particular, do not use NULL when the ASCII null character (NUL) is desired. Provide your own definition

#define NUL '\0'

如果你一定要的话。