我一直在試圖編寫一個程序,該程序需要用戶輸入的數字列表,這些數字存儲在二維數組中(像矩陣)。該程序以矩陣形式打印出來,然後使用函數對陣列進行轉置,然後打印轉置陣列。以2維數組爲參數調用函數時出錯(C++)
下面是程序:
#include <iostream>
using namespace std;
void transpose(int length, int width, int input[][length], int output[][width])
{
for(int j=0; j<length; j++)
for(int i=0; i<width; i++)
{
output[j][i]=input[i][j];
}
}
int main()
{
int width;
int length;
cout << "enter the width followed by the length of the matrix: ";
cin >> width >> length;
int input[width][length];
int output[length][width];
cout << "enter elements \n";
for(int j=0; j<length; j++)
for(int i=0; i<width; i++)
{
cin >> input[i][j];
}
cout << "your matrix is: \n";
for(int j=0; j<length; j++) //output in matrix form
for(int i=0; i<width; i++)
{
cout << input[i][j] << " ";
if(i==width-1)
cout << endl;
}
/*for(int j=0; j<length; j++) //to check if transpose works
for(int i=0; i<width; i++)
{
output[j][i]=input[i][j];
}*/
transpose(length, width, input, output);
cout << "the transpose is: \n";
for(int j=0; j<width; j++)
for(int i=0; i<length; i++)
{
cout << output[i][j] << " ";
if(i==length-1)
cout << endl;
}
return 0;
}
當我嘗試調用主函數,它給出了錯誤:「否調用‘轉’匹配功能」,然後說:「候選人功能不可行:沒有已知的從'int [width] [length]'到'int(*)[length]'的第三個參數的轉換「。我不明白爲什麼。我嘗試過搜索,但我沒有運氣(儘管完全有可能我不瞭解解決方案,或者我正在尋找錯誤的東西)。
如果相關,我使用Xcode在Mac上。
使用'的std :: VECTOR'代替。 – Jarod42
我建議將矩陣存儲在1D數組中,並只傳遞一個指向函數第一個值的指針。像int input [] [length]這樣的參數非常混亂。 – dari
看看這個:http://www.programmingsimplified.com/c-program-transpose-matrix – SerhatCan