简体   繁体   中英

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

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.

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.

数组中的元素保证是连续的,因此两种情况下的布局都是相同的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM