Categories
arrays c++ multidimensional-array pointers undefined-behavior

May I treat a 2D array as a contiguous 1D array?

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? How about the fourth line?

It’s up to interpretation. While the contiguity requirements of arrays don’t leave much to the imagination in terms of how to layout a multidimensional arrays (this has been pointed out before), notice that when you’re doing p[1234] you’re indexing the 1234th element of the zeroth row of only 80 columns. Some interpret the only valid indices to be 0..79 (&p[80] being a special case).

Information from the C FAQ which is the collected wisdom of Usenet on matters relevant to C. (I do not think C and C++ differ on that matter and that this is very much relevant.)