[英]2D array transpose matrix in C
#include <stdio.h>
void read_array( int row, int col, int a[row][col]);
void fill_arr(int row, int col,int b[row][col], int a[row][col]);
void print_arr(int row, int col, int a[row][col]);
int main(void){
int r1,c1;
printf("Enter number of rows>");
scanf("%d", &r1);
printf("Enter number of columns>");
scanf("%d", &c1);
int arr[r1][c1];
read_array(r1,c1,arr);
int arr2[c1][r1];
fill_arr(c1,r1,arr2,arr);
print_arr(c1,r1,arr2);
}
void read_array( int row, int col, int a[row][col]){
int i,j;
printf("Enter values for %d rows with each row having %d numbers> ", row, col);
for(i=0; i<row; i++){
for(j=0; j<col; j++){
scanf("%d", &a[i][j]);
}
}
}
void fill_arr(int row, int col,int b[row][col], int a[row][col]){
int i,j;
for(i=0; i<row;i++){
for(j=0; j<col; j++){
b[i][j] = a[j][i];
}
}
}
void print_arr(int row, int col, int a[row][col]){
int i,j;
printf("Transpose: \n");
for(i=0; i<row; i++){
for(j=0; j<col; j++){
printf("%d ", a[i][j]);
}
printf("\n");
}
}
/*Example for a 3x4 matrix with 1-12 as input:
Expected output:
1 5 9
2 6 10
3 7 11
4 8 12
Actual output:
1 4 7
2 5 8
3 6 9
4 7 10
/*
I'm trying to make a program to make a transpose matrix of a given matrix.我正在尝试制作一个程序来制作给定矩阵的转置矩阵。 Here, the last value of a column is being repeated for some reason.
在这里,由于某种原因,列的最后一个值被重复。 How can I fix this?
我怎样才能解决这个问题? (I'm aware there are other working codes for transpose matrix on stackoverflow. I need to find the problem in THIS code).
(我知道在stackoverflow上还有其他用于转置矩阵的工作代码。我需要在此代码中找到问题)。
I believe you are mixing up c1
and r1
in the call to fill_array()
.我相信您在调用
fill_array()
时混淆了c1
和r1
。
Also, that function should be called transpose_array()
or copy_transposed()
.此外,应该将 function 称为
transpose_array()
或copy_transposed()
。 fill
suggests you're filling with some fixed value or with zeros. fill
建议您使用一些固定值或零填充。
Hope this is useful.希望这是有用的。
void fill_arr(int row, int col,int b[col][row], int a[row][col]){
int i,j;
for(i=0; i<row;i++){
for(j=0; j<col; j++){
b[j][i] = a[i][j];
}
}
}
void print_arr(int row, int col, int a[row][col]){
int i,j;
printf("Transpose: \n");
for(i=0; i<row; i++){
for(j=0; j<col; j++){
printf("%d ", a[i][j]);
}
printf("\n");
}
}
int main(void){
int r1,c1;
printf("Enter number of rows>");
scanf("%d", &r1);
printf("Enter number of columns>");
scanf("%d", &c1);
int arr[r1][c1];
read_array(r1,c1,arr);
int arr2[c1][r1];
fill_arr(r1,c1,arr2,arr);
print_arr(c1,r1,arr2);
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.