简体   繁体   English

3d数组在内存中是连续的,那么2d呢?

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

If I declare a 2d c-style array of 如果我声明一个2d c风格的数组

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? int data[X*Y]但这有保证吗?

Let's say for simplicity we are using standard compilers on an x86 architecture. 让我们假设为简单起见,我们在x86架构上使用标准编译器。 Now what about 那怎么样?

int data[X][Y][Z] ? 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. 我通常使用单个向量作为带有偏移行* NumCols + col的2d数组,并且有一个内联函数来为我计算它,但我对这个问题的3d数组感兴趣。 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. 是的,C中任何顺序的多维数组都是连续的。 They're just "arrays of arrays", so to speak. 他们只是“数组阵列”,可以这么说。 Plenty more at the comp.lang.c FAQ, section 6, Arrays and Pointers . 还有更多关于comp.lang.c常见问题解答,第6节,数组和指针

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. 阵列在物理内存中可能不是连续的,但这对您来说无关紧要。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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