Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to free 2d array in C?

I have the following code:

int **ptr = (int **)malloc(sizeof(int*)*N);  for(int i=0;i<N;i++)       ptr[i]=(int*)malloc(sizeof(int)*N)); 

How can I free ptr using free? Should I loop over ptr and free ptr[i] or should I just do

free(ptr)  

and ptr will be freed?

like image 761
lina Avatar asked Apr 14 '11 16:04

lina


People also ask

Can we free array in C?

Ad. Example 1: array is allocated on the stack ("automatic variable") and cannot be released by free . Its stack space will be released when the function returns.

How do you initialize a 2D array?

To declare a 2D array, specify the type of elements that will be stored in the array, then ( [][] ) to show that it is a 2D array of that type, then at least one space, and then a name for the array. Note that the declarations below just name the variable and say what type of array it will reference.

Can you pass a 2D array in C?

A 2-D array can be easily passed as a parameter to a function in C. A program that demonstrates this when both the array dimensions are specified globally is given as follows.


2 Answers

Just the opposite of allocation:

for(int i = 0; i < N; i++)     free(ptr[i]); free(ptr); 
like image 131
Donotalo Avatar answered Sep 21 '22 20:09

Donotalo


You will have to loop over ptr[i], freeing each int* that you traverse, as you first suggest. For example:

for (int i = 0; i < N; i++) {     int* currentIntPtr = ptr[i];     free(currentIntPtr); } 
like image 38
James Bedford Avatar answered Sep 25 '22 20:09

James Bedford