How to free a two dimensional array using a function allocated memory using int ** ptr?
For example I use allocArray( &ptrArray, row, column); to allocate the array.
What is the proper procedure to free the allocated memory using this function:
void freeArray( int *** pA, int row, int column)
#include <stdio.h>
#include <stdlib.h>
void allocArray( int *** pA, int row, int column)
{
int i, j, count;
*pA = (int **) malloc(row * sizeof(int *));
for (int i =0; i<row; ++i)
{
(*pA)[i] = (int *) malloc( column * sizeof(int));
}
// Note that pA[i][j] is same as *(*(pA+i)+j)
count = 0;
for (i = 0; i < row ; i++)
for (j = 0; j < column; j++)
(*pA)[i][j] = ++count; // OR *(*(pA+i)+j) = ++count
for (i = 0; i < row; i++) {
for (j = 0; j < column; j++) {
printf("%d ", (*pA)[i][j]);
}
printf("\n");
}
}
// How to free a two dimensional array allocated memory using int ** ptr?
void freeArray( int *** pA, int row, int column)
{
}
void test_array_allocation()
{
int i, j;
int row = 3, column = 4;
int ** ptrArray;
allocArray( &ptrArray, row, column);
printf("test_array_allocation\n");
for (i = 0; i < row; i++) {
for (j = 0; j < column; j++) {
printf("%d ", (ptrArray)[i][j]);
}
printf("\n");
}
freeArray(&ptrArray, row, column); // free allocated memory
}
int main(int argc, const char * argv[]) {
test_array_allocation();
return 0;
}
(*pA)[i], then free*pA. You might want to redesign your code though. It is rarely a good sign when things likeint ***start showing up. - Filipe Gonçalves