我可以取数组的最后一个元素的地址吗? [英] May I take the address of the one-past-the-end element of an array?

查看:40
本文介绍了我可以取数组的最后一个元素的地址吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
通过下标获取最后一个数组元素的地址:C++ 标准是否合法?

int array[10];

int* a = array + 10;   // well-defined
int* b = &array[10];   // not sure...

最后一行是否有效?

推荐答案

是的,您可以将地址移到数组末尾之外,但不能取消引用它.对于包含 10 个项目的数组, array+10 会起作用.&array[10] 是否真的会导致未定义的行为(如果会,是否真的应该),(委员会等)曾多次争论过.它的底线是,至少根据当前的标准(C 和 C++),它正式导致未定义的行为,但是如果有一个编译器实际上不起作用,则任何参数中的任何人都无法查找或引用它.

Yes, you can take the address one beyond the end of an array, but you can't dereference it. For your array of 10 items, array+10 would work. It's been argued a few times (by the committee, among others) whether &array[10] really causes undefined behavior or not (and if it does, whether it really should). The bottom line with it is that at least according to the current standards (both C and C++) it officially causes undefined behavior, but if there's a single compiler for which it actually doesn't work, nobody in any of the arguments has been able to find or cite it.

有一次我的记忆对了一半——这是(部分)官方缺陷报告给委员会,至少一些委员会成员(例如 Tom Plum)认为措辞已经改变,所以它不会导致未定义行为.OTOH,DR 的日期是 2000 年,并且状态仍然是正在起草",因此它是否真的已修复或可能是否已修复尚有待商榷(我还没有查看 N3090/3092 以弄清楚).

For once my memory was half correct -- this was (part of) an official Defect Report to the committee, and at least some committee members (e.g., Tom Plum) thought the wording had been changed so it would not cause undefined behavior. OTOH, the DR dates from 2000, and the status is still "Drafting", so it's open to question whether it's really fixed, or ever likely to be (I haven't looked through N3090/3092 to figure out).

然而,在 C99 中,它显然不是未定义的行为.

In C99, however, it's clearly not undefined behavior.

这篇关于我可以取数组的最后一个元素的地址吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆