C语言 在函数C中分配内存二维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15062718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Allocate memory 2d array in function C
提问by serhii
How to allocate dynamic memory for 2d array in function ? I tried this way:
如何在函数中为二维数组分配动态内存?我试过这种方式:
int main()
{
int m=4,n=3;
int** arr;
allocate_mem(&arr,n,m);
}
void allocate_mem(int*** arr,int n, int m)
{
*arr=(int**)malloc(n*sizeof(int*));
for(int i=0;i<n;i++)
*arr[i]=(int*)malloc(m*sizeof(int));
}
But it doesn't work.
但它不起作用。
回答by Grijesh Chauhan
Your code is wrong at *arr[i]=(int*)malloc(m*sizeof(int));because the precedenceof the []operator is higher than the *deference operator: In the expression *arr[i], first arr[i]is evaluated then *is applied. What you need is the reverse (dereference arr, then apply []).
您的代码是错误的*arr[i]=(int*)malloc(m*sizeof(int));,因为优先级的的[]操作者比更高*顺从操作:在该表达式中*arr[i],第一arr[i]被评估然后*被应用。你需要的是相反的(取消引用arr,然后应用[])。
Use parentheses like this: (*arr)[i]to override operator precedence. Now, your code should look like this:
使用这样的括号:(*arr)[i]覆盖运算符优先级。现在,您的代码应如下所示:
void allocate_mem(int*** arr, int n, int m)
{
*arr = (int**)malloc(n*sizeof(int*));
for(int i=0; i<n; i++)
(*arr)[i] = (int*)malloc(m*sizeof(int));
}
To understand further what happens in the above code, read this answer.
要进一步了解上述代码中发生的情况,请阅读此答案。
It is important that you always deallocate dynamically allocated memory explicitly once you are done working with it. To free the memory allocated by the above function, you should do this:
使用完动态分配的内存后,始终明确地释放动态分配的内存,这一点很重要。要释放上述函数分配的内存,您应该这样做:
void deallocate_mem(int*** arr, int n){
for (int i = 0; i < n; i++)
free((*arr)[i]);
free(*arr);
}
Additionally, a better way to create a 2D array is to allocate contiguous memorywith a single malloc()function call as below:
此外,创建二维数组的更好方法是使用单个函数调用分配连续内存,malloc()如下所示:
int* allocate_mem(int*** arr, int n, int m)
{
*arr = (int**)malloc(n * sizeof(int*));
int *arr_data = malloc( n * m * sizeof(int));
for(int i=0; i<n; i++)
(*arr)[i] = arr_data + i * m ;
return arr_data; //free point
}
To deallocate this memory:
要释放此内存:
void deallocate_mem(int*** arr, int* arr_data){
free(arr_data);
free(*arr);
}
Notice that in the second technique malloc is called only two times, and so in the deallocation code free is called only two times instead of calling it in a loop. So this technique should be better.
请注意,在第二种技术中 malloc 仅被调用两次,因此在释放代码中 free 仅被调用两次,而不是在循环中调用它。所以这个技术应该更好。
回答by Cyrille Faucheux
If your array does not need to be resized (well, you can, but il will be a bit more complicated), there is an easier/more efficient way to build 2D arrays in C.
如果你的数组不需要调整大小(好吧,你可以,但会更复杂一点),有一种更简单/更有效的方法来用 C 构建二维数组。
Take a look at http://c-faq.com/aryptr/dynmuldimary.html.
看看http://c-faq.com/aryptr/dynmuldimary.html。
The second method (for the array called array2) is quite simple, less painful (try to add the tests for mallocs' return value), and way more efficient.
第二种方法(对于名为 array2 的数组)非常简单,痛苦更少(尝试添加对 malloc 返回值的测试),并且效率更高。
I've just benchmarked it, for a 200x100 array, allocated and deallocated 100000 times:
我刚刚对它进行了基准测试,对于一个 200x100 的数组,分配和释放了 100000 次:
- Method 1 : 1.8s
- Method 2 : 47ms
- 方法一:1.8s
- 方法二:47ms
And the data in the array will be more contiguous, which may speed things up (you may get some more efficient techniques to copy, reset... an array allocated this way).
并且数组中的数据将更加连续,这可能会加快速度(您可能会获得一些更有效的技术来复制、重置...以这种方式分配的数组)。
回答by TheMan
Consider this: Just single allocation
考虑一下:只是单一分配
int** allocate2D(int m, int n)
{
int **a = (int **)malloc(m * sizeof(int *) + (m * n * sizeof(int)));
int *mem = (int *)(a + m);
for(int i = 0; i < m; i++)
{
a[i] = mem + (i * n);
}
return a;
}
To Free:
免费:
free(a);
回答by Smit Patel
Rather allocating the memory in many different block, one can allocate this in a consecutive block of memory. Do the following:
与其在许多不同的块中分配内存,不如将其分配在连续的内存块中。请执行下列操作:
int** my2DAllocation(int rows,int columns)
{
int i;
int header= rows *sizeof(int *);
int data=rows*cols*sizeof(int);
int ** rowptr=(int **)malloc(header+data);
if(rowptr==NULL)
{
return NULL:
}
int * buf=(int*)(rowptr+rows);
for(i=0;i<rows;i++)
{
rowptr[i]=buf+i*cols;
}
return rowptr;
}
回答by Nanobrains
I have tried the following code for allocating memory to 2 dimensional array.
我已经尝试了以下代码来为二维数组分配内存。
#include<stdio.h>
#include<malloc.h>
void main(void)
{
int **p;//double pointer holding a 2d array
int i,j;
for(i=0;i<3;i++)
{
p=(int**)(malloc(sizeof(int*)));//memory allocation for double pointer
for(j=(3*i+1);j<(3*i+4);j++)
{
*p = (int*)(malloc(sizeof(int)));//memory allocation for pointer holding integer array
**p = j;
printf(" %d",**p);//print integers in a row
printf("\n");
p++;
}
}
}
Output of the above code is:-
上面代码的输出是:-
1 2 3
1 2 3
4 5 6
4 5 6
7 8 9
7 8 9
In order to understand 2 dimensional array in terms of pointers, we need to understand how it will be allocated in memory, it should be something like this:-
为了从指针的角度理解二维数组,我们需要了解它将如何在内存中分配,它应该是这样的:-
1 2 3
1000 --> 100 104 108
4 5 6
1004 --> 200 204 208
7 8 9
1008 --> 300 304 308
from the above, we understand that, when we allocate memory to pointer p which is a double pointer, it is pointing to an array of integers, so in this example, we see that the 0x1000 is pointer p.
从上面我们了解到,当我们为指针p分配内存时,它是一个双指针,它指向的是一个整数数组,所以在这个例子中,我们看到0x1000是指针p。
This pointer is pointing to integer pointer *p which is array of integers, when memory is allocated inside the inner for loop, during first iteration the pointer is 0x100 which is pointing to integer value 1, when we assign **p = j. Similarly it will be pointing to 2 and 3 in the next iterations in the loop.
这个指针指向整数指针 *p,它是整数数组,当内存在内部 for 循环内分配时,在第一次迭代期间,指针是 0x100,它指向整数值 1,当我们分配 **p = j 时。类似地,它将在循环的下一次迭代中指向 2 和 3。
Before the next iteration of the outer loop, double pointer is incremented, inside the next iteration, as is seen in this example the pointer is now at 0x1004 and is pointing to integer pointer which is an array of integers 4,5,6 and similarly for the next iterations in the loop.
在外循环的下一次迭代之前,双指针递增,在下一次迭代中,如本例所示,指针现在位于 0x1004 并指向整数指针,该指针是整数 4、5、6 的数组,类似用于循环中的下一次迭代。
回答by autistic
That is an unnecessarily complicated way of allocating space for an array. Consider this:
这是为数组分配空间的一种不必要的复杂方法。考虑一下:
int main(void) {
size_t m = 4, n = 3;
int (*2D_array)[m];
2D_array = malloc(n * sizeof *2D_array);
free(2D_array);
return 0;
}
回答by Kaushal Gangwar
Try the following code:
试试下面的代码:
void allocate_mem(int*** arr,int n, int m)
{
*arr=(int**)malloc(n*sizeof(int*));
for(int i=0;i<n;i++)
*(arr+i)=(int*)malloc(m*sizeof(int));
}
回答by ashutosh
2d Array dynamically array using malloc:
使用 malloc 动态排列二维数组:
int row = 4;
int column = 4;
int val = 2;
// memory allocation using malloc
int **arrM = (int**)malloc (row*sizeof(int*));
for (int i=0;i<row;i++)
{
arrM[i] = (int*)malloc(column*sizeof(int));
// insert the value for each field
for (int j =0;j<column;j++,val++)
{
arrM[i][j] = val;
}
}
// De-allocation
for (int i=0;i<row;i++)
{
free(arrM[i]);
}
free(arrM);
arrM = 0;
//
// Now using New operator:
//
int **arr = new int*[row];
int k = 1;
for (int i=0;i<row;i++)
{
arr[i] = new int[column];
// insert the value for each field
for (int j =0;j<column;j++,k++)
{
arr[i][j] = k;
}
}
cout<<"array value is = "<<*(*(arr+0)+0)<<endl;
cout<<"array value is = "<<*(*(arr+3)+2)<<endl;
// Need to deallcate memory;
for (int i=0;i<row;i++)
{
delete [] arr[i];
}
delete []arr;
arr = 0;

