我想编写一个程序来转置一个n*n矩阵,但是代码输出了一些奇怪的东西。它没有转置矩阵。假设我想要转置一个矩阵{(1,2,3), {4,5,6),(7,8,9)},结果与原始矩阵基本相同,但存在一些我不知道的奇怪行为。
#include<iostream>
#include<iomanip>
using namespace std;
void transpose(int* p, int n);
#define M 20
int main()
{
int a[M][M];
int n;
int* p;
cout << "The size of a matrix is: ";
cin >> n;
cout << "Input a matrix: " << endl;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cin >> a[i][j];
p = &a[0][0];
transpose(p, n);
cout << "Now, the matrix is: " << endl;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << setw(4) << a[i][j];
}
cout << endl;
}
return 0;
}
void transpose(int* p, int n)
{
for (int i = 0; i < n; i++)
{
for (int j = i; j < n; j++)
{
int temp = *(p + i * n + j);
*(p + i * n + j) = *(p + j * n + i);
*(p + j * n + i) = temp;
}
}
}