할당 된 메모리를 사용하여 주어진 행렬을 조 변경하는 프로그램을 작성 중입니다. 이 함수는 정사각형 행렬 NxN (행 == cols)과 완벽하게 작동하지만 MxN 행렬 (행! = cols)과 충돌합니다. C++로 행렬 전치시키기
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;
}
}
문제입니다
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)'를 사용하라. –