问题描述
我了解 C/C++ 中 NULL 常量的用途,并且我了解它需要在内部以某种方式表示.
I understand the purpose of the NULL constant in C/C++, and I understand that it needs to be represented some way internally.
我的问题是:对于 C/C++ 中的对象来说,0 地址是无效的内存位置是否有一些根本原因?或者我们是否理论上因为这个保留而浪费"了一个字节的内存?
My question is: Is there some fundamental reason why the 0-address would be an invalid memory-location for an object in C/C++? Or are we in theory "wasting" one byte of memory due to this reservation?
推荐答案
空指针实际上不必为 0.在 C 规范中保证,当在指针的上下文中给出常量 0 值时,它是编译器将其视为 null,但是如果您这样做
The null pointer does not actually have to be 0. It's guaranteed in the C spec that when a constant 0 value is given in the context of a pointer it is treated as null by the compiler, however if you do
char *foo = (void *)1;
--foo;
// do something with foo
您将访问 0 地址,不一定是空指针.在大多数情况下,实际情况确实如此,但这不是必需的,因此我们实际上不必浪费那个字节.虽然,在更大的图片中,如果它不是 0,它必须是某个东西,所以一个字节被浪费了某处
You will access the 0-address, not necessarily the null pointer. In most cases this happens to actually be the case, but it's not necessary, so we don't really have to waste that byte. Although, in the larger picture, if it isn't 0, it has to be something, so a byte is being wasted somewhere
由于注释中的混淆,删除了 NULL 的使用.此外,这里的主要信息是空指针!= 0,这里有一些 C/伪代码,显示了我试图提出的观点."请不要实际尝试编译它或担心类型是否正确;意思很明确.
Edited out the use of NULL due to the confusion in the comments. Also, the main message here is "null pointer != 0, and here's some C/pseudo code that shows the point I'm trying to make." Please don't actually try to compile this or worry about whether the types are proper; the meaning is clear.
这篇关于为什么 NULL/0 是对象的非法内存位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)