2

Suppose we have the following program:

#include <iostream>
int main()
{
    int a[2][3]{{1, 2, 3},
                {4, 5, 6}};
    a[0][4] = -50;
    std::cout << a[1][1] << std::endl; // prints -50
}

Is this guaranteed to work or it is undefined behavior? As long as I know it is guaranteed that &a[0][2] + 1 == &a[1][0], but on the other side a[0] is an array itself and the valid indices for it are 0..2.

Edit: If it is forbidden by the standard, is there any specific reason to be forbidden? The 'duplicate' question does not answer that. I need to know the technical reason behind this. Why would it be worse if it was allowed?

Lassie
  • 853
  • 8
  • 18
  • 1
    I believe that a 2D statically-allocated array must be consecutive in memory by definition (i.e., by he language standard). And since its dimensions are known during compilation-time, this operation should therefore be well defined (to do exactly what you're expecting it to). – goodvibration Nov 27 '19 at 20:03
  • 2
    No, this is undefined behaviour. – ChrisMM Nov 27 '19 at 20:05
  • 1
    In C++, it's not enough to get the address of something. It's often important how you *got* that address. One of the big reasons for this is to helps compilers in reasoning about code to perform better optimizations. While it seems like the address you get from `a[0][4]` will always be that of `a[1][1]` doing it that way violates the rules of the language. For example, maybe the compiler could see that nothing every gets written to the elements of `a[1]` after it's initialized (there is no assignment to an element of `a[1]`) and could optimize the code to just `std::cout<<5< – François Andrieux Nov 27 '19 at 20:35

0 Answers0