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?
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.
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.
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.
Just the opposite of allocation:
for(int i = 0; i < N; i++) free(ptr[i]); free(ptr);
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With