简体   繁体   English

动态分配2D数组

[英]Allocating 2D array dynamically

My task is to make a 2D array 2xn from values given in A and B which have n elements. 我的任务是根据A和B中包含n个元素的值制作2dn二维数组。

I found this way to allocate memory for 2D array and it works but I don't understand if or why it is correct 我发现了这种为2D数组分配内存的方法,它可以工作,但是我不知道它是否正确或为什么正确

int **tab2D(int A[],int B[],int n)
{
    int **newTab = malloc(n*sizeof(int*));
    newTab[0] = A;
    newTab[1] = B;
    return newTab;
}

I know there are other ways to do this but I'm curious about this one. 我知道还有其他方法可以做到这一点,但我对此感到很好奇。

As I understand your code it should work like this. 据我了解您的代码,它应该像这样工作。

int **tab2D(int A[],int B[],int n)

can be seen as 可以看作是

int **tab2D(int *A,int *B, int n)

so you pass pointers to the two arrays which are already allocated. 因此,您将指针传递给已经分配的两个数组。 You then allocate some memory for the pointers-to-pointers 然后,您为指针到指针分配一些内存

 int **newTab = malloc(n*sizeof(int*));

which I think should be 我认为应该是

 int **newTab = malloc(2*sizeof(int*));

instead, because you have A and B , which are both the same length n , I assume. 相反,因为您拥有AB ,它们的长度均为n ,所以我假设。 Then you dereference the new pointer-to-pointers and assign the pointers to your arrays 然后,取消引用新的指向指针的指针,并将指针分配给数组

newTab[0] = A;
newTab[1] = B;

which could be written as 可以写成

*newTab = A;
*(newTab + 1) = B;

This is not a 2D array of int s, is an array of pointers to int . 这不是int的2D数组,而是一个指向int的指针的数组。

It works because each element of the array points to an address containing an array of int s 之所以有效,是因为数组的每个元素都指向一个包含int数组的地址

A similar code using the stack, just to show why it works: 使用堆栈的类似代码,只是为了说明其工作原理:

int a[] = {1, 2};
int b[] = {3, 4};
int *arr[] = {a, b};

A real 2D array is supposed to work in contiguous areas (without fragmentation), you can use pointers to VLA's to achieve this: 真正的2D数组应该可以在连续区域中工作(没有碎片),您可以使用指向VLA的指针来实现此目的:

int rows, cols;

scanf("%d %d", &rows, &cols);

int (*arr)[cols] = malloc(sizeof(int [rows][cols]));

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

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