Sloth Sloth - 3 months ago 15
C Question

Allocate memory 2d array in function 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 ?

Answer

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.

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

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

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
} 

To deallocate memory:

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

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.

Comments