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

查看:157
本文介绍了分配内存的二维数组中的函数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));
} 

不过,这是行不通的。 有人可以摆正自己的错误?

But it doesn't work. Someone can to put right my mistakes ?

推荐答案

您code是错误的,在 *常用3 [I] =(INT *)malloc的(M *的sizeof(INT)) ; ,因为 precedence [] 运营商高于 * 尊重运营商因此在EX pression *改编[I] ,第改编[I] 计算则 * 应用。凡为你需要的是相反的。

Your code is wrong at *arr[i]=(int*)malloc(m*sizeof(int)); because precedence of [] operator higher then * deference operator so in expression *arr[i], first arr[i] evaluates then * applied. Where as your need is reverse.

不要像(* ARR)[我] 覆盖运营商precedence。

Do like (*arr)[i] to override operator precedence.

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

要理解上面的内存分配code阅读:<一href="http://stackoverflow.com/questions/19240540/dynamically-allocating-array-explain/19240932#19240932">Dynamically分配数组解释。

To understand above memory allocation code read: Dynamically allocating array explain.

重要应始终释放动态分配的内存明确一个你工作,完成它。
为了释放由上述函数分配的内存:

Important you should always deallocate dynamically allocated memory explicitly one you work done with it.
To free memory allocated by above function:

void deallocate_mem(int*** arr, int n){
    for (int i = 0; i < n; i++)
        free((*arr)[i]);
    free(*arr); 
}

此外,第二个办法:<一href="http://stackoverflow.com/questions/17477234/difference-b-w-allocating-memory-to-2d-array-in-1-go-or-row-by-row">Allocate连续的内存
一个更好的办法可以是在分配内存继续内存单的malloc()函数调用如下:

Additionally, second way: Allocate contiguous memory
A better way can be to allocate memory in continue memory with 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被称为只有两次,所以在释放code免费只调用从两次代替调用一个循环 - 所以这个技术应该更好地

So do you notice in second technique malloc is called only two times and so in deallocation code free is called only from two times in stead calling in a loop - So this technique should be better.

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

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