[英]transpose non-square matrix in C
我试图在转置矩阵上工作的每个人都是我的代码到目前为止。
void Transpose(int mt[][10], int m, int n)
{
int c,d,temp;
for (c = 0; c < m; c++)
{
for (d = c+1; d < n; d++)
{
temp = mt[c][d];
mt[c][d]=mt[d][c];
mt[d][c] = temp;
}
}
}
void print(int pose[][10], int m, int o)
{
int i,j;
for(i = 0; i < m; i++)
{
for(j = 0; j < o; j++)
{
printf("%d\n",pose[j][i]);
}
}
}
int main()
{
/*The body of your source code will go here */
int a[4][5] = {{1,2,3,4,5},{6,7,8,9,10},{10,9,8,7,6},{5,4,3,2,1}};
printf("ARRAY: %d",a[][5]);
Transpose();
return (0);
}
这是我的打印和转置矩阵的功能,但现在我试图将数组传递给我的主要功能。 我只是想知道如何声明main中的数组可以传递给函数。 谢谢
您的Transpose
声明与您的使用不符。 因为它被声明为:
void Transpose(int mt[][10], int m, int n) {...}
它应该被调用
Transpose(a, 4, 5);
另外, 10
为什么? 而且,声明
printf("ARRAY: %d", a[][5]);
不太可行。
您应该为变量选择更好的名称。 而不是m
和n
,使用nRows
和nColumns
。 使用row
和column
而不是i
和j
。
您可以使用以下代码执行此操作。
#include<stdio.h>
// Print Matrix
void printArr(int *A, int row,int col)
{
int i,j;
for(i=0;i<row;i++)
{
printf("\n");
for(j=0;j<col;j++)
printf("%d\t",*(A+(col*i)+j));
}
}
//Find the Transpose(TA) of Matrix(A)
void Transpose(int *A,int *TA,int row,int col)
{
int i,j;
for(i=0;i<row;i++)
for(j=0;j<col;j++)
*(TA+(j*row)+i)=*(A+(col*i)+j);
}
// Start of Main
int main()
{
int A[4][5]={{1,2,3,4,5},{6,7,8,9,10},{10,9,8,7,6},{5,4,3,2,1}};
int *TA=malloc(sizeof(int)*4*5); // Allocate Memory for TA
int i,j;
printf("Matrix A:");
printArr(A,4,5); //Print Array A
Transpose(A,TA,4,5); //Call Transpose
printf("\nTranspose Matrix A:");
printArr(TA,5,4); // Print Array TA
return 0;
}
输出:
Matrix A:
1 2 3 4 5
6 7 8 9 10
10 9 8 7 6
5 4 3 2 1
Transpose Matrix A:
1 6 10 5
2 7 9 4
3 8 8 3
4 9 7 2
5 10 6 1
C编程语言不像其他编程语言那样记住数组的长度。 这使得处理多维数组变得困难。
要将多维数组作为参数传递给C,您必须在编译时知道数组的维数:
#define HEIGHT 10
#define WIDTH 13
void function_prototype(int M[HEIGHT][WIDTH]) {
access M normally with M[y][x]
}
或者你必须传递一维数组和长度作为参数:
void function_prototype(int* M, int height, int width) {
access M as M[y * width + x]
}
这很麻烦,但这是你为极快的阵列访问付出的代价。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.