简体   繁体   English

如何在RAM存储器中进行数据布局?

[英]How data layout in RAM memory?

I have a basic architecture based question. 我有一个基于基本架构的问题。 How does multi dimensional arrays layout in memory? 多维数组如何在内存中布局? Is this correct that data layout linearly in memory? 数据在内存中线性排列是否正确? Is so, is it correct that in row major order data store based on row orders (first row store, then second row ...) and in column major data stores based on columns? 是这样,基于行顺序的行主要订单数据存储(第一行存储,然后第二行...)以及基于列的列主要数据存储是否正确?

Thanks 谢谢

Each array is stored in sequence, naturally. 每个数组自然都按顺序存储。 It makes no sense to spread data all over the place. 将数据分散到整个地方毫无意义。

Example in C: 在C中的示例:

int matrix[10][10];
matrix[9][1] = 1234;
printf("%d\n", matrix[9][1]); // prints 1234
printf("%d\n", ((int*)matrix)[9 * 10 + 1]); // prints 1234

Of course there is nothing enforcing you to organize data this way, if you want to make a mess you can do it. 当然,没有什么可以强迫您以这种方式组织数据,如果您想弄乱,可以这样做。

For example, if instead of using an array of arrays you decide to dynamically allocate your matrix: 例如,如果您决定不使用数组来决定动态分配矩阵,则:

int **matrix;
matrix = malloc(10 * sizeof(int*));
for (int i = 0; i < 10; ++i)
    matrix[i] = malloc(10 * sizeof(int));

The above example is most likely still stored in sequence, but certainly not in a contiguous manner, because there are 11 different memory blocks allocated and the memory manager is free to allocate them wherever it makes sense to it. 上面的示例很可能仍按顺序存储,但肯定不是连续存储的,因为分配了11个不同的存储块,并且内存管理器可以随意分配它们。

The representation of an array depends upon the programming language. 数组的表示形式取决于编程语言。 Most languages (the C abortion and its progeny being notable exceptions) represent arrays using a descriptor. 大多数语言(C流产及其后代是明显的例外)都使用描述符来表示数组。 The descriptor specifies the number of dimensions the upper and lower bounds of each dimension, and where the data is located. 描述符指定每个维的上下边界的维数以及数据的位置。

Usually, the all the data for the array is stored contiguously. 通常,数组的所有数据都连续存储。 Even when stored contiguously the ordering depends upon the language. 即使连续存储,其顺序也取决于语言。 In some languages [0, 0, 0] is stored next to [1, 0, 0] (Column Major—eg FORTRAN)). 在某些语言中,[0,0,0]存储在[1,0,0]的旁边(主列-例如FORTRAN)。 In others [0, 0, 0] is next to [0, 0, 1] (and [0, 0, 0] and [1, 0, 0] are apart—row major—eg, Pascal). 在其他情况下,[0,0,0]紧挨着[0,0,1](并且[0,0,0]和[1,0,0]分开-行主要-例如,帕斯卡)。 Some languages, such as Ada, leave the ordering up to the compiler implementation. 某些语言(例如Ada)将顺序留给编译器实现。

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

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