I have a function which creates a 2D array:
float** createMatrix(int x, int y){
float** array= malloc(sizeof(float*) * y);
for(int i=0; i<y; i++)
array[i] = malloc(sizeof(float) * x);
return array;
}
Now I can create a 2D array:
float** temp=createMatrix(2,2);
I also have a function, for e.g., which transposes my “matrix” (2D array):
float** matrixTranspose(float** m, int x, int y){
float** result=createMatrix(y, x);
for(int i=0; i<y; i++){
for(int j=0;j<x; j++) result[j][i]=m[i][j];
}
return result;
}
Now if I do this:
temp=matrixTranspose(temp,2,2);
what happens with the old memory previously allocated to temp? My transpose function allocates new memory chunk. Obviously I would have to somehow free “old temp” after the Transposition, but how (elegantly)?
Your
freecan mirror your allocation:But if you assign to
tempthe new matrix created bymatrixTranspose, then you’ll lose your pointer to that memory. So keep track of that with another pointer, or assign the result ofmatrixTransposeto another pointer:If you consider your matrices as mutable, you could also transpose them in place: rather than allocating a new matrix in the
matrixTransposefunction, you move around the numbers in the existing array. You can do this in place with onefloat temp.