Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a 3d array contiguous in memory, what about a 2d?

Tags:

c++

arrays

c

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.

like image 684
bjackfly Avatar asked Oct 23 '13 17:10

bjackfly


People also ask

Are 2D arrays contiguous in memory?

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.

Is a 3D array contiguous?

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.

What is the difference between 2D array and 3D array?

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).

How is a 2 dimensional array stored in memory?

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.


2 Answers

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.

like image 74
Carl Norum Avatar answered Sep 30 '22 17:09

Carl Norum


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.

like image 34
jxh Avatar answered Sep 30 '22 19:09

jxh