Home > Backend Development > C++ > Why Does Treating a 2D Array as a 1D Array in C/C Lead to Undefined Behavior?

Why Does Treating a 2D Array as a 1D Array in C/C Lead to Undefined Behavior?

Patricia Arquette
Release: 2024-12-15 17:48:12
Original
966 people have browsed it

Why Does Treating a 2D Array as a 1D Array in C/C   Lead to Undefined Behavior?

Treating a 2D Array as a 1D Array: Undefined Behavior

In C and C , multidimensional arrays are stored contiguously in memory. However, accessing a multidimensional array using single-dimensional indexing can lead to undefined behavior.

Consider the following code:

int a[25][80];
a[0][1234] = 56; // Line 2
int* p = &a[0][0];
p[1234] = 56; // Line 4
Copy after login

Line 2:
This line attempts to access an element that is outside the bounds of the array a[25][80]. The first dimension of a has a size of 25, but line 2 tries to access the 1235th element, which is beyond the valid range. This results in undefined behavior because it violates the language definition.

Line 4:
This line also triggers undefined behavior. The array a has 25 * 80 = 2000 elements, while p points to the start of the array. The expression p[1234] therefore tries to access the 1235th element of the array, which is outside the valid range. Subscripting an array using a pointer that exceeds its bounds is considered undefined behavior.

Constant Expressions:
The undefined behavior in the above code also manifests in constant expressions. The following code will not compile due to undefined behavior:

constexpr int f(const int (&a)[2][3])
{
    auto p = &a[0][0];
    return p[3]; // Undefined behavior
}
int main()
{
    constexpr int a[2][3] = { 1, 2, 3, 4, 5, 6, };
    constexpr int i = f(a);
}
Copy after login

This demonstrates that undefined behavior in constant expressions is still illegal, and compilers will reject such code.

The above is the detailed content of Why Does Treating a 2D Array as a 1D Array in C/C Lead to Undefined Behavior?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template