简体   繁体   English

我需要帮助来了解这一行代码来动态创建数组吗?

[英]I need help understanding this line of code dynamically creating an array?

I am starting to get more practice with malloc and although there is nothing wrong with the code it executes properly. 我开始对malloc进行更多的练习,尽管正确执行的代码没有错。

int *arr = (int *)malloc(x * y * sizeof(int));
int i, j, r;

for(i=0; i<x; i++){
    for(j=0; j<y; j++){
        r = 0 + rand() % 7;
        *(arr + i*y + j) = r; 
   //I dont understand the left hand portion of the above line.

//x and y are both 5000

I found it online and before I found it, I had tried doing the exact same thing but I guess my syntax was wrong. 我在网上找到了它,在找到它之前,我曾尝试做完全相同的事情,但是我想我的语法是错误的。 Anyways, I need help understanding the line that has the comment next to it 无论如何,我需要帮助来了解旁边有评论的行

*(arr + i*y + j) is trying to store value in the array element denoted by array[i][j] . *(arr + i*y + j)试图将值存储在由array[i][j]表示的数组元素中。

What value you receive from r in the previous line, is being fed to the array[i][j] th element of the array. 从R个接收在先前行什么值,被馈送到阵列的阵列的[I] [j] 元件。

arr locates the base element of the array, adding i*y locates to the (i+1)th row of the array (index count starts from 0 in C) , and adding j to that produces the exact column(j+1 th column) in which array[i][j] is located. arr定位数组的基本元素,将i*y添加到数组的第(i + 1)行(索引计数从C中的0开始) ,然后向其添加j生成确切的列(第j + 1个)列)其中array[i][j]所在。

The block of memory allocated in the first line is being used as a two-dimensional matrix. 第一行中分配的内存块被用作二维矩阵。 For more information, read this: row/column-major order . 有关更多信息,请阅读: row / column-major order

Here is a diagram: 这是一个图:

大行

That diagram probably should be transposed based on the use of y in the expression, but the concept is the same. 该图可能应该基于表达式中y的使用而进行转置,但是概念是相同的。 The numbers in each box is the linear offset. 每个框中的数字是线性偏移量。 As you can see, the offset into the linear block of memory is equal to the row index multiplied by the width plus the column index, or i*y + j . 如您所见,线性存储器块中的偏移量等于行索引乘以宽度加列索引,即i*y + j

Normally what you do is declare a 2D array int arr[5000][5000]; 通常,您要做的是将2D数组声明为int arr[5000][5000]; or the equivalent malloc code. 或等效的malloc代码。

What is done in this case, is to declare a single dimensional array, but to use it as a 2-D array. 在这种情况下,要做的是声明一维数组,但将其用作二维数组。 This way is also possible, but it involves the extra overhead of constantly checking the location. 这种方法也是可行的,但是它涉及不断检查位置的额外开销。

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

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