常量 0 在 C 和 C++ 中用作空指针.但正如问题指向特定固定地址的指针" 似乎可以使用分配固定地址.在任何系统中,对于访问地址 0 的任何低级任务,是否有任何可想象的需求?
The constant 0 is used as the null pointer in C and C++. But as in the question "Pointer to a specific fixed address" there seems to be some possible use of assigning fixed addresses. Is there ever any conceivable need, in any system, for whatever low level task, for accessing the address 0?
如果有,如何用 0 为空指针和所有来解决?
If there is, how is that solved with 0 being the null pointer and all?
如果不是,那么是什么确定没有这种需要?
If not, what makes it certain that there is not such a need?
无论是在 C 中还是在 C++ 中,空指针值都与物理地址 0
没有任何关联.您在源代码中使用常量0
来设置指向空指针值的指针,这只不过是一个语法糖.编译器需要将其转换为特定平台上用作空指针值的实际物理地址.
Neither in C nor in C++ null-pointer value is in any way tied to physical address 0
. The fact that you use constant 0
in the source code to set a pointer to null-pointer value is nothing more than just a piece of syntactic sugar. The compiler is required to translate it into the actual physical address used as null-pointer value on the specific platform.
换句话说,源代码中的 0
没有任何物理重要性.例如,它可能是 42
或 13
.IE.语言作者,如果他们愿意的话,可以这样做,这样你就必须执行 p = 42
以便将指针 p
设置为空指针值.同样,这并不意味着必须为空指针保留物理地址 42
.编译器需要将源代码 p = 42
翻译成机器代码,这些机器代码将填充实际的物理空指针值(0x0000
或 0xBAAD
) 进入指针 p
.这正是使用常量 0
时的情况.
In other words, 0
in the source code has no physical importance whatsoever. It could have been 42
or 13
, for example. I.e. the language authors, if they so pleased, could have made it so that you'd have to do p = 42
in order to set the pointer p
to null-pointer value. Again, this does not mean that the physical address 42
would have to be reserved for null pointers. The compiler would be required to translate source code p = 42
into machine code that would stuff the actual physical null-pointer value (0x0000
or 0xBAAD
) into the pointer p
. That's exactly how it is now with constant 0
.
另请注意,C 和 C++ 都没有提供严格定义的功能,允许您将特定的物理地址分配给指针.因此,您关于如何将 0 地址分配给指针"的问题正式没有答案.您根本无法为 C/C++ 中的指针分配特定地址.但是,在实现定义的功能领域,显式整数到指针的转换旨在产生这种效果.所以,你会这样做
Also note, that neither C nor C++ provides a strictly defined feature that would allow you to assign a specific physical address to a pointer. So your question about "how one would assign 0 address to a pointer" formally has no answer. You simply can't assign a specific address to a pointer in C/C++. However, in the realm of implementation-defined features, the explicit integer-to-pointer conversion is intended to have that effect. So, you'd do it as follows
uintptr_t address = 0;
void *p = (void *) address;
注意,这和做不一样
void *p = 0;
后者总是产生空指针值,而前者在一般情况下不会.前者通常会产生一个指向物理地址 0
的指针,它可能是也可能不是给定平台上的空指针值.
The latter always produces the null-pointer value, while the former in general case does not. The former will normally produce a pointer to physical address 0
, which might or might not be the null-pointer value on the given platform.
这篇关于我可以想访问地址零吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!