& a [n]是否有效,其中n是数组的大小? [英] Is &a[n] valid, where n is the size of the array?
问题描述
考虑以下简单代码对数组进行排序.
Consider the following simple code to sort an array.
int myarray[4] = {};
std::sort(myarray, myarray + 4);
我知道创建一个指向C样式数组末尾的指针是有效的.
I know that it is valid to create a pointer to one past the end of a C-style array.
我最近看过这样的代码:
I've recently seen code like this:
std::sort(myarray, &myarray[4]);
我不确定这是否有效,因为即使元素值未用于任何东西,它也会取消引用数组边界之外的元素.
I'm not sure this is valid, because it dereferences an element outside the array bounds, even though the element value is not used for anything.
这是有效的代码吗?
推荐答案
A[i]
在语法上等效于*(A + i)
,用于数组或指针A
.
因此&A[i]
在语法上等同于&(*(A + i))
.
A[i]
is syntactically equivalent to *(A + i)
for an array or pointer A
.
So &A[i]
is syntactically equivalent to &(*(A + i))
.
当*(A + i)
没有未定义的行为时,&(*(A + i))
的行为将与A + i
相同.
When *(A + i)
does not have undefined behavior, &(*(A + i))
will behave identically to A + i
.
问题在于myarray[4]
在语法上等同于*(myarray + 4)
,后者会取消引用数组边界之外的位置.根据标准,这是未定义的行为.
The problem is that myarray[4]
is syntactically equivalent to *(myarray + 4)
, which dereferences a location out of the array's bounds. That is undefined behavior according to the standard.
因此,您绝对应该优先选择myarray + 4
而不是&myarray[4]
-后者是未定义的行为.
So you should absolutely prefer myarray + 4
over &myarray[4]
- the latter is undefined behavior.
&myarray[4]
具有"正确"行为,大多数(如果不是全部的话)编译器并没有根据标准豁免其具有 undefined 行为.
That &myarray[4]
has "correct" behavior with most - if not all - compilers does not exempt it from having undefined behavior according to the standard.
这篇关于& a [n]是否有效,其中n是数组的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!