简体   繁体   English

在C中为指针分配0 vs NULL

[英]Assigning 0 vs NULL to a pointer in C

I wondered today about that it is possible to assign an integer 0 to a pointer, ie doing the same like assigning NULL. 我今天想知道是否可以为指针分配一个整数0,即可以像分配NULL一样进行操作。 Until today I assumed, this was new with C++. 直到今天,我还认为这是C ++的新功能。 Has this been a feature of C from the beginning or was it relaxed with a more recent language-standard? 从一开始,这是C的功能吗?还是随着最新的语言标准而放松?

Per The C Programming Language by Kernighan and Ritchie, 1978, page 192: 根据Kernighan和Ritchie的《 The C Programming Language》 ,1978年,第192页:

However, it is guaranteed that assignment of the constant 0 to a pointer will produce a null pointer distinguishable from a pointer to any object. 但是,可以确保将常量0分配给指针将产生一个空指针,该指针可与指向任何对象的指针区分开。

I cannot speak to the history before that. 在此之前,我无法谈论历史。

According to the C Standard (6.3.2.3 Pointers) 根据C标准(6.3.2.3指针)

3 An integer constant expression with the value 0 , or such an expression cast to type void *, is called a null pointer constant .66) If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function. 3 值为0的整数常量表达式 ,或将其转换为void *类型的表达式称为空指针常量 .66)如果将空指针常量转换为指针类型,则所得的指针称为空指针,保证比较不等于指向任何对象或函数的指针。

In K&R first edition (pre-ANSI), page 97-98 we have some example code with: 在K&R第一版(pre-ANSI)中,第97-98页,我们有一些示例代码,其中包括:

#define NULL 0 /* pointer value for error report */

"C guarantees that no pointer that validly points at data will contain zero, so a return value of zero can be used to signal an abnormal event... We write NULL instead of zero, however, to indicate more clearly that this is a special value for a pointer. In general, integers cannot meaningfully be assigned to pointers." “ C保证有效指向数据的指针都不会包含零,因此返回值零可用于表示异常事件……我们写NULL而不是零,但是,更清楚地表明这是一个特殊的情况。通常,不能有意义地将整数分配给指针。”

Clearly here 0 , and therefore NULL , is not typed as a pointer but an int . 显然,这里的0 (即NULL )不是类型为指针,而是int It's worth noting that void * was not introduced until edition 2 (ANSI). 值得注意的是直到版本2(ANSI)才引入void *

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM