I want to transpose a matrix in C, with as little memory use as possible. Therefore it is not an option to simply create a copy of the matrix, fill it in, and delete the other one afterwards. I thus want to do every swap on the matrix itself, with 1 temp variable to reuse. Matrix elements are indexed with pointer arithmetic, but as far as I’m aware, these are correct. The problem now being that the function doesn’t result in any changes. The matrix struct is dynamically allocated and has the folowing structure;
typedef struct {
int rows;
int cols;
int** data;
} matrix;
The transpose function I wrote now looks as follows;
void transpose(matrix* m){
int i,j,temp;
for(i=0;i<m->row;i++){
for(j=0;j<m->col;j++){
temp=*((*(m->data+i))+j);
*((*(m->data+i))+j)=*((*(m->data+j))+i);
*((*(m->data+j))+i)=temp;
}
}
}
I already tried starting the function with
int* temp=(int*)malloc()sizeof(int);
and ending with
free(temp);
That gives me an error in Visual Studio about adres acess. Any tips?
You are indexing over the entire matrix in your for-loop (and I’m assuming your matrix is square) … you only need to index over the lower-triangle or upper triangle of the matrix, and then swap those positions with the corresponding index in the opposing triangle of the matrix. To transpose the diagonal of the matrix, you only need to swap the upper-half of the diagonal with the lower half. By indexing across the entire matrix you end up doing a double-transpose which will end up returning the exact same result as the original matrix.