问题描述
如果我以下列方式遍历二维数组的元素,这是未定义的行为吗?
Is it undefined behavior if I go through the elements of a 2D array in the following manner?
int v[5][5], i;
for (i = 0; i < 5*5; ++i) {
v[i] = i;
}
再说一次,它甚至可以编译吗?(我现在不能尝试,我不在家.)如果没有,那么想象一下我以某种方式获得了一个指向第一个元素的指针并使用 taht 而不是 v[i]
.
Then again, does it even compile? (I can't try it right now, I'm not at home.) If it doesn't, then imagine I somehow acquired a pointer to the first element and using taht instead of v[i]
.
推荐答案
从指向第一个元素的指针访问多维数组的元素对于不属于第一个数组的元素是未定义行为 (UB).
Accessing elements of a multidimensional array from a pointer to the first element is Undefined Behavior (UB) for the elements that are not part of the first array.
>
给定 T array[n]
,array[i]
是对所有 i >= n 的 UB-land 的直接旅行.即使 T
是 U[m]
.即使它是通过一个指针.正如其他人所提到的,确实对数组有很强的要求(例如 sizeof(int[N]) == N*sizeof(int)
),但没有明确例外,所以什么也做不了关于它.
Given T array[n]
, array[i]
is a straight trip to UB-land for all i >= n. Even when T
is U[m]
. Even if it's through a pointer. It's true there are strong requirements on arrays (e.g. sizeof(int[N]) == N*sizeof(int)
), as mentioned by others, but no exception is explicitly made so nothing can be done about it.
我没有官方参考资料,因为据我所知,C++ 标准将细节留给了 C89 标准,而且我对 C89 或 C99 标准都不熟悉.相反,我参考了 comp.lang.c FAQ:
I don't have an official reference because as far as I can tell the C++ standard leaves the details to the C89 standard and I'm not familiar with either the C89 or C99 standard. Instead I have a reference to the comp.lang.c FAQ:
[...] 根据官方解释,访问 (&array[0][0])[x] 的行为没有为 x >= NCOLUMNS 定义.
这篇关于C/C++:这是未定义的行为吗?(二维数组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!