简体   繁体   English

多维线性数组C

[英]Multidimensional linear arrays C

I was reading this article: How to loop through multi-dimensional arrays quickly . 我正在阅读这篇文章: 如何快速遍历多维数组

I would like to know more about "linear multidimensional arrays" but I can't find anything of relevance and would like to know if any of you have seen anything like it. 我想了解有关“线性多维数组”的更多信息,但是我找不到任何相关的信息,并且想知道你们中是否有人看到过类似的东西。

Specifically I would like to understand better how to access a multidimensional array (that's declared as single dimension) using math. 具体来说,我想更好地了解如何使用数学访问多维数组(被声明为单维)。 It sounds awesome! 听起来很棒!

Statically allocate 静态分配

In c, if you want to create a 3x4 array for example you need to do like following code: 在c中,例如,如果要创建3x4数组,则需要执行以下代码:

int array1[3][4]; // statically allocate 3x4 integer in stack. The memory will be organize like this:
// [[0, 1, 2, 3] // first row
//  [4, 5, 6, 7] // second row
//  [8, 9, 10, 11]

It would be the same if you declare a 12 int array 如果声明一个12 int数组,它将是相同的

int array2[12]; // memory will be
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

So: array1[2][3] == array[2* (number of columns) + 3] = 11 因此: array1[2][3] == array[2* (number of columns) + 3] = 11

Both are the same, the first one is easier to read than the second one. 两者相同,第一个比第二个更容易阅读。 The compiler knows the dimension of the array, so it will calculate the address for you. 编译器知道数组的维数,因此它将为您计算地址。

Dynamically allocate 动态分配

In this case you don't know the dimension of the array, so. 在这种情况下,您不知道数组的维数。 Create a 3x4 array will like this 创建一个3x4数组将像这样

int **array1 = (int **) malloc(rows * sizeof(int *)); // allocate 4 pointers
for (int i = 0; i < rows; i++) {
  array1[i] = (int *) malloc(columns * sizeof(int)); // allocate memory for each row.
}

// the memory will be organized like this
// array1 [row0pointer, row1pointer, row2pointer]
// some where else in the memory: ... row0 ... row1 ... row2 ..

It's not optimize because you need memory to store pointers, and when you access each member you have to access through pointers. 它不是最佳的,因为您需要内存来存储指针,并且在访问每个成员时必须通过指针进行访问。 So you can allocate a single array that has rows * columns member instead: 因此,您可以分配具有行*列成员的单个数组:

int *array2 = (int *) malloc(rows * columns * sizeof(int));

// then when you want to access array2[i][j] you can easily access 
array2[i * columns + j]

The same with n-dimensions array. 与n维数组相同。

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

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