我正在编写一个程序来使用分配的内存转置给定的矩阵。该函数与方阵 NxN (rows==cols) 完美配合,但它与 MxN 矩阵 (rows != cols) 一起崩溃。请帮忙
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;
}
}