我正在編寫一個程序,用分配的內存轉置給定的矩陣。該函數對方矩陣NxN(rows == cols)起作用,但與MxN矩陣(行!= cols)碰撞。請幫助在C++中轉置矩陣
void transpose(int **matrix, int *row, int *col)
{
// dynamically allocate an array
int **result;
result = new int *[*col]; //creates a new array of pointers to int objects
// check for error
if (result == NULL)
{
cout << "Error allocating array";
exit(1);
}
for (int count = 0; count < *col; count++)
{
*(result + count) = new int[*row];
}
// transposing
for (int i = 0; i<*row; i++)
{
for (int j = i+1; j<*col; j++)
{
int temp = *(*(matrix + i) + j);
*(*(matrix + i) + j) = *(*(matrix + j) + i);
*(*(matrix + j) + i) = temp;
}
}
for (int i = 0; i<*row; i++)
{
for (int j = 0; j<*col; j++)
{
*(*(result + i) + j) = *(*(matrix + i) + j);
cout << *(*(result + i) + j) << "\t";
}
cout << endl;
}
}
'new'在失敗時會拋出異常。如果你希望它在失敗時返回'null',可以使用'new(nothrow)'(儘管這很奇怪)。 – 2013-02-13 08:08:05