Home >Backend Development >C++ >Is Accessing a 2D Array as a Contiguous 1D Array in C Undefined Behavior?
Can a 2D Array Be Treated as a Contiguous 1D Array?
Subscripting in C results in pointer addition followed by indirection. Consider the following code:
int a[25][80]; a[0][1234] = 56; int* p = &a[0][0]; p[1234] = 56;
Does the second line invoke undefined behavior? What about the fourth line?
Answer:
Both lines do result in undefined behavior.
As per the C standard, pointer addition to an array element results in valid behavior only if the resulting index is within the bounds of the array. In this case, a[0] has size 80, and indices outside of this range are undefined.
Explanation:
Subscripting is equivalent to the following:
a[0][1234] == *(a[0] + 1234)
Since a[0] points to the first element of the first row of a, the pointer addition a[0] 1234 attempts to access an element beyond the end of the row. This results in undefined behavior.
Similarly, the fourth line attempts to modify a value outside the bounds of the row:
p[1234] == *(p + 1234)
Even though p points to the first element of a, attempting to modify an element beyond the bounds of its underlying row results in undefined behavior.
It is important to note that this type of undefined behavior is not detected by the compiler. Therefore, it is essential to ensure that pointer arithmetic operations remain within the bounds of valid array elements during runtime.
The above is the detailed content of Is Accessing a 2D Array as a Contiguous 1D Array in C Undefined Behavior?. For more information, please follow other related articles on the PHP Chinese website!