I have a function that allocates a two dimensional array within a function returning a pointer to the array. Creating the array requires an array of pointers each of which contains the address of a row of the two dimensional array.
How do I correctly free these two malloc()
calls outside of this function once I am done with this array?
int** allocateMatrix(int rows, int cols)
{
int* arr = malloc(rows*cols*sizeof(int));
int** matrix = malloc(rows*sizeof(int*));
int i;
for(i=0; i<rows; i++)
{
matrix[i] = &(arr[i*cols]);
}
return matrix;
}
The function is used like this:
int** 2d_arr = allocateMatrix(row,cols);
Thanks!