I have been working on a code displaying the result of transposing 2D arrays containing integers. My aim was to replace the original array with its transpose rather than create a copy and I have run into a problem along the way regarding memory allocation. In the beginning I get number of rows (m) and columns (n) via scanf() and then allocate memory for the array in the main() function as below:
int **mtr=(int **)malloc(m*sizeof(int *));
for(int i=0;i<m;i++)
mtr[i]=(int *)malloc(n*sizeof(int));
Then I call my function for transposing arrays that looks as follows:
void transposeMatrix(int m,int n,int mtr[m][n])
{
int temp[m][n];
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
temp[i][j]=mtr[i][j];
}
}
for(int i=0;i<m;i++)
free(mtr[i]);
free(mtr);
mtr=(int **)malloc(n*sizeof(int *));
for(int i=0;i<n;i++)
mtr[i]=(int *)malloc(m*sizeof(int));
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
mtr[i][j]=temp[j][i];
}
}
}
My aim was to first store the values of original 'mtr' in temporary 'temp' array, then free memory allocated to 'mtr' and then allocate memory once more switching rows with columns in order to use the same 'mtr' back in the main(). However at line:
mtr[i]=(int *)malloc(m*sizeof(int));
I get "error:assignment to expression with array type". Shouldn't mtr[i] by freed at that point? Does anyone know where the problem might be?