Are these null pointers, or are they pointers to address 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?
p1
、p2
和 p3
中的哪一个(我添加了 p8
和 p9
) 将是 空指针(即 == 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?
推荐答案
p1
和 p2
为空指针;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.
p8
和 p9
在 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 的指针?
基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07