[quote name='Cornstalks' timestamp='1331441179' post='4921046']
I know, the obvious answer is to go read the standard, and I've tried looking it up, but I'm not entirely sure what specific section it would be under, and the one I did check ended up confusing me by the time I finished the paragraph.
The relevant section would be 8.3.4 for all versions of the C++ standard.
[/quote]
Thanks, I had read 4.2.1, but didn't feel like that was the actual answer to the question. I think 8.3.4.8 & 9 really got into what I was after.
Arrays are guaranteed to be contiguous and, as a result, arrays of arrays are guaranteed to be contiguous as well. Thus, the array myArray[4][4] can be thought of as a contiguous chunk of 16 ints. If you pass in the address of the first element to a function that expects a pointer to 16 ints, then there won't be a problem, with the standard or otherwise.
Yes, that's what my intuition said, but I wasn't sure if there was a guarantee about how this memory was laid out, which this directly depends on. Turns out the standard states that arrays (and arrays of arrays) are stored row-wise, which guarantees the memory layout such that myArray[0][5] should be the same as myArray[1][1]. myArray[0][5] just looks soooo...
wrong, knowing it's a 4x4 array. But hey, I guess it's valid.
You can also dereference your 2D array to make it 1D:
doStuff(*myArray);
Yeah, that's what I'm doing in the first method (though I've used array subscripting).
Another way of handling this is with a good old-fashioned union:union _myArray
{
int arr2d[4][4];
int arr1d[16];
} myArray;
I actually prefer this approach as it would make what you're doing more explicit to anyone reading the code.
Someone correct me if I'm wrong, but my understanding of section 9.5 of the standard ("Unions") states that "at most one of the data members can be active at any time," which, as I understand it, means that only the most recently set member has a well defined value (though people do this
a lot without issues, but I think setting one member of a union and then reading another is technically undefined, not just in terms of what you get out, but in terms of if it'll even work). However, I'm wondering if this just might be valid in this case (section 9.5.1 talks about being able to access common members between PODs). I guess it depends on if arr2d and arr1d can be considered PODs with common members (16 ints, that is). Can anyone shed some light on this, and correct me if my first sentence is wrong?