这些是空指针,还是指向地址 0 的指针?

Are these null pointers, or are they pointers to address 0?(这些是空指针,还是指向地址 0 的指针?)

本文介绍了这些是空指针,还是指向地址 0 的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我写

int zero = 0;

void *p1 = (void *)0;
void *p2 = (void *)(int)0;
void *p3 = (void *)(0 /*no-op, but does it affect the next zero?*/, 0);

void *p4 = (void *)zero;    // For reference, this is a pointer to address zero
void *p5 = 0;               // For reference, this is a null pointer
void *p6 = NULL;            // For reference, this is a null pointer
void *p7 = nullptr;         // For reference, this is a null pointer (C++11)

static const int static_zero_1 = 0;       // Is this a literal zero when used?
static const int static_zero_2 = 1 - 1;   // No "literals 0" per se... is it?
void *p8 = (void *)static_zero_1;   // I have seen weird substitution rules...
void *p9 = (void *)static_zero_2;   // do they apply for NULL too?

p1p2p3 中的哪一个(我添加了 p8p9) 将是 空指针(即 == NULL,可能是也可能不是地址零),它们中的哪些是是地址为零的指针(可能是也可能不是 ==NULL)?

which of p1, p2, and p3 (edit: I added p8 and p9) would be null pointers (i.e. == NULL, may or may not be address zero), and which of them would be pointers with the address zero (may or may not be == NULL)?

如果答案在 C 和 C++ 中不同,那么它们分别是什么?

If the answer is different in C and C++, what is it in each of them?

推荐答案

p1p2 为空指针;p3 是实现定义的,并且可能是别的东西.(逗号运算符不能是一个常量表达式.和一个非常量的映射指针的整数值 0 是实现定义的.)C 是此处与 C++ 相同.

p1 and p2 are null pointers; p3 is implementation defined, and may be something else. (A comma operator cannot be part of a constant expression. And the mapping of a non-constant integral value 0 to a pointer is implementation defined.) C is identical to C++ here.

p8p9 在 C++ 中都是空指针,但在 C 中不是.

p8 and p9 are both null pointers in C++, but not in C.

关于您对 static_zero_2 的评论,没有任何一种语言都要求存在文字零,任何地方.g++ 将 NULL 定义为编译器内置的 __null,例如,您可以使用 (1 - 1)'' 或任何其他计算结果为 0 的常量表达式.

With regards to your comment on static_zero_2, there is no requirement in either language that a literal zero be present, anywhere. g++ defines NULL as the compiler built-in __null, for example, and you can use (1 - 1), or '', or any other constant expression evaluating to 0.

这篇关于这些是空指针,还是指向地址 0 的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:这些是空指针,还是指向地址 0 的指针?

基础教程推荐