Home > Backend Development > C++ > Does Accessing a 2D Array Element Using Pointer Arithmetic Beyond Its Bounds Result in Undefined Behavior?

Does Accessing a 2D Array Element Using Pointer Arithmetic Beyond Its Bounds Result in Undefined Behavior?

Mary-Kate Olsen
Release: 2024-12-31 12:35:09
Original
520 people have browsed it

Does Accessing a 2D Array Element Using Pointer Arithmetic Beyond Its Bounds Result in Undefined Behavior?

Can a 2D Array Be Treated as a Concatenated 1D Array?

Consider the following code snippet:

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

Question: Does the code access the array beyond its bounds, resulting in undefined behavior?

Answer: Yes, both lines 2 and 4 exhibit undefined behavior.

In C , array indexing is essentially pointer arithmetic. When accessing a[i][j], the compiler effectively translates it to *(a[i] j). Similarly, p[i] refers to *(p i).

In this case, the array a has dimensions 25 x 80. The first row of the array, a[0], contains 80 elements (ranging from a[0][0] to a[0][79]) and is allocated at a contiguous memory location.

By accessing a[0][1234], the code attempts to access an element at index 1234 in the first row, despite a[0] only containing elements within the range [0, 79]. This is out of bounds and triggers undefined behavior.

The same logic applies to line 4. While p points to the first element of a[0], the array is still dimensioned as 25 x 80. Accessing p[1234] is essentially an out-of-bounds pointer arithmetic operation, once again leading to undefined behavior.

Furthermore, as Language Lawyer pointed out in the comments, a similar code snippet using a constexpr would fail to compile due to the compiler detecting such undefined behaviors in a constant expression:

constexpr int f(const int (&a)[2][3])
{
    auto p = &a[0][0];
    return p[3];
}

int main()
{
    constexpr int a[2][3] = { 1, 2, 3, 4, 5, 6, };
    constexpr int i = f(a);
}
Copy after login

This compiles correctly because accessing p[3] using a constexpr triggers the compiler to detect the undefined behavior and throw an error.

The above is the detailed content of Does Accessing a 2D Array Element Using Pointer Arithmetic Beyond Its Bounds Result in 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