C/C++: Is this undefined behavior? (2D arrays)

前端 未结 5 1752
渐次进展
渐次进展 2020-12-04 02:29

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;
}         


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-04 03:30

    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.

    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.

    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:

    [...] according to an official interpretation, the behavior of accessing (&array[0][0])[x] is not defined for x >= NCOLUMNS.

提交回复
热议问题