C++地址存在吗?
假设我在 C++ 中有以下代码:
char buffer[SIZE];
char * ptr = &buffer[SIZE];
其中 ptr
的值永远不会被取消引用。这对于 C++ 来说合法吗?即使用距数组最后一个元素一步的内存地址(例如作为要比较的特殊值)?
Suppose I have the following in C++:
char buffer[SIZE];
char * ptr = &buffer[SIZE];
where ptr
's value is never dereferenced. Is this even legal to do C++? That is use the memory address one stride from the last element of an array (say as a special value to compare to)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你说:
那么是的,这是合法的。 C++ 标准特别允许您以这种方式使用数组的尾数,并且在(例如)使用迭代器时广泛使用它。
编辑:但请参阅 litb 和 Steve Jessop 的评论。如果你想完全政治正确,你可能想要:
无论哪种方式,最后一个地址都是一个有效的地址 - 也许不太清楚的问题(据我所知)是是否允许你取消引用它。
If you said:
then yes, it is legal. You are specifically allowed by the C++ standard to use the one-past-the-end of an array in this manner, and it is used extensively when (for example) working with iterators.
Edit: But see comments by litb and Steve Jessop. If you want to be entirely politcally correct, you probably want:
Either way, the one-past-the-end address is a valid address - the perhaps not quite clear issue (as I understand it) is whether you are allowed to dereference it.
您的意思是
&buffer[SIZE]
?是的,它在 C++ 中是合法的。 ptr 的值是缓冲区的末尾,大多数标准算法都可以将其用作缓冲区的 end() 迭代器。You meant
&buffer[SIZE]
? Yes it is legal in C++. The value of ptr is one past end of buffer, most standard algorithms can use it as end() iterator for buffer.