问题描述
我问自己,如果这些线code的可以在C和用C产生不确定的行为++。
我试着回答每一个点读什么标准说有关数组下标(C 6.5.6 - 8)。我没有贴全款,因为它是pretty长。
1 int a[10];
2 int b = a[9]; // ok
3 int c = a[10]; // UB
4 int* d = (a + 10); // ok
5 int* e = &a[10]; // ok from C99 (& and [] are ignored, pointer is not deferenced), // UB in pre C99
6 int* f = &a[11]; // ok from C99, UB in pre c99
int* g = a;
7 int* h = g + 15; // ok
I think that the same aswers should be valid for C++
Are these lines valid in C and in C++, have I misunderstood the standard?
Neither 6 nor 7 are valid, because they do not perform pointer arithmetic inside an existing array (including the one-past-the-end pointer). Everything else is essentially correct.
In C only: Given that a[i]
is identical to *(a + i)
, and &*p
is always just p
without evaluating *p
, 5 should always be fine, although you're right that C89 does not specify this and this was only added in C99. (This is not true at all in C++, where operators can be overloaded and there is no mention of combining &
and *
.)
From n1570 (draft to C11), in paragraph 8 of 6.5.6 Additive operators:
C++ contains very similar wording (e.g. C++11, 5.7/5).
这篇关于数组指针运算 - 法律和未定义行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!