If I declare a 2d c-style array of
int data[X][Y]
I am assuming that the compiler will create this as a single array similar to
int data[X*Y]
but is this guaranteed?
Let's say for simplicity we are using standard compilers on an x86 architecture. Now what about
int data[X][Y][Z]
?
Does the compiler create this as a contiguous block of memory and just do some fiddling with the offsets?
I normally use a single vector for a 2d array with offsets row * NumCols + col and have an inline function to calc it for me, but I was interested in a 3d array for this question. I should also ask if anyone has done this with a single vector and what would be the offset logic as well.
Memory is allocated contiguously when a two-dimensional array is declared as follows: int matrix [ 2 ][ 5 ] = {{ 1 , 2 , 3 , 4 , 5 },{ 6 , 7 , 8 , 9 , 10 }}; However, when we use a function such as malloc to create a two-dimensional array, there are variations in how memory can be allocated.
Yes they are contiguous. I would say the fact "an array" (i.e. singular) is contiguous infers that a multi-dimensional one is. Each array within it must be contiguous and the outer array must be a contiguous collection of those arrays... Save this answer.
DIFFERENCE : Every 2D array is a multidimensional array but the other way round is not necessary(for example a 3D array is also a multidimensional array but its surely not 2D).
A 2D array is stored in the computer's memory one row following another. The address of the first byte of memory is considered as the memory location of the entire 2D array.
Yes, multi-dimensional arrays of any order in C are contiguous. They're just "arrays of arrays", so to speak. Plenty more at the comp.lang.c FAQ, section 6, Arrays and Pointers.
The resulting arrays will be contiguous in the virtual memory area assigned to your process. The arrays may not be contiguous in physical memory, but that shouldn't matter to you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With