Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it legal to access a bidimensional array as if it where a one-dimensional one? [duplicate]

Possible Duplicate:
May I treat a 2D array as a contiguous 1D array?

Consider the following code:

int array2d[10][10];
int *array1d = array2d[0];

I never heard of an implementation where it wouldn't work, but is it legal to access and manipulate array2d via array1d? Which section of the standard allows this? Is there anything in the standard preventing implementations from inserting extra space or padding between each of the second level arrays (not that its needed, but still)?

Bonus question: Is there a way to access array2d as an int[100] which does not require a reinterpret_cast or a C-style one?

like image 559
K-ballo Avatar asked May 25 '12 21:05

K-ballo


1 Answers

If memory serves, the standard gives this as an example of something that's officially undefined behavior, but essentially always works. [Edit: Here's what I was thinking of: C99, §J.2 (Undefined behavior):

  • An array subscript is out of range, even if an object is apparently accessible with the given subscript (as in the lvalue expression a[1][7] given the declaration int a[4][5])

I'm not entirely certain that applies though, as you're getting the address of the beginning of an array and converting it to a simple pointer to the underlying type.]

Arrays are required to be contiguous, so it cannot insert any padding between elements of an array. That's true whether you have an array of int or an array of arrays.

like image 111
Jerry Coffin Avatar answered Oct 20 '22 12:10

Jerry Coffin