在函数C中分配内存二维数组 [英] Allocate memory 2d array in function C

查看:33
本文介绍了在函数C中分配内存二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在函数中为二维数组分配动态内存?我试过这种方式:

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));
} 

但它不起作用.

推荐答案

你的代码在 *arr[i]=(int*)malloc(m*sizeof(int)); 因为[] 运算符的优先级高于* 顺从运算符:在表达式 *arr[i] 中,首先计算 arr[i] 然后 * 是应用.你需要的是相反的(取消引用arr,然后应用[]).

Your code is wrong at *arr[i]=(int*)malloc(m*sizeof(int)); because the precedence of 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​​] 来覆盖运算符优先级.现在,您的代码应如下所示:

Use parentheses like this: (*arr)[i] to override operator precedence. Now, your code should look like this:

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); 
}

此外,创建二维数组的更好方法是 使用单个 malloc() 函数调用分配连续内存,如下所示:

Additionally, a better way to create a 2D array is to allocate contiguous memory with a single malloc() function call as below:

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
} 

要释放此内存:

void deallocate_mem(int*** arr, int* arr_data){
    free(arr_data);
    free(*arr);
}

请注意,在第二种技术中,malloc 只被调用了两次,因此在释放代码中,free 只被调用了两次,而不是在循环中调用.所以这个技术应该更好.

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.

这篇关于在函数C中分配内存二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆