i want to transpose matrix the code works when column=row and when column>row but when row > column i get wrong answers
all of the code :
#include <stdio.h>
#include <stdlib.h>
int main() {int row,column,tmp;
scanf("%d",&row);
scanf("%d",&column);
int *image=(int*)malloc(sizeof(int)*row*column);
int *target=(int*)malloc(sizeof(int)*row*column);
for(int i=0;i<row;i ){
for(int j=0;j<column;j ){
scanf("%d",&tmp);
image[i*column j]=target[i*column j]=tmp;
}
}
transpose(row,column,target,image);
for (int i = 0; i< m; i ) {
for (int j = 0; j < n; j )
printf("%d\t", target[i*column j]);
printf("\n");
}}
void transpose(int row, int column,int* target,int* image) {
for (int i = 0; i < row; i ) {
for (int j = 0; j < column; j ) {
target[j * column i] = image[i * column j];
}
}
}
my matrix in the image and i want to the transpose in the target .
input :
1 2
3 4
5 6
output(what i get from my code) :
1 3 5
5 4 6
output (what should i get ) :
1 3 5
2 4 6
input work :
1 2 3
4 5 6
output :
1 4
2 5
3 6
CodePudding user response:
As @Bob_ suggests, you are mis-calculating the offset into your target array.
Your source image has column
columns and row
rows; but the transposed image as row
columns and column
rows! (By the way - that's a poor choice of identifiers; consider num_columns
and num_rows
as parameters to the transpose function). So I believe you need to have:
target[j * row i] = image[i * column j];
in your inner loop.
CodePudding user response:
To understand what you are doing, I recommend you to print index value computed in you algorithm.
The problem is that i
can be greater than column
(same thing with j
and row
). You have to use %
to improve your code.