I am developing a function to transpose an array (i.e. a[i][j] => a[j][i]). To test the function, the following array is created: array[4][3] = {...} But a compiler returns the error:
E:\CodeBlock\2_7.cpp||In function 'int main()':|
E:\CodeBlock\2_7.cpp|13|error: cannot convert 'int (*)[3]' to 'const int* const*' for argument '1' to 'int** transpose(const int* const*, unsigned int, unsigned int)'|
||=== Build finished: 1 errors, 0 warnings (0 minutes, 1 seconds) ===|
As I understand the type of array
is int**
. So, how can transpose
function take up this array?
#include <iostream>
#include <cstdlib>
using namespace std;
int ** transpose(const int * const * m, unsigned rows, unsigned cols);
int main()
{
int array[4][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}};
int ** arrayT = {};
arrayT = transpose(array, 4, 3);
return 0;
}
int ** transpose(const int * const * m, unsigned rows, unsigned cols)
{
int **tr = new int *[cols];
for (unsigned i = 0; i<cols; i++){
tr[i] = new int[rows];
for (unsigned j = 0; j < rows; j++) {
tr[i][j] = m[j][i];
}
}
return tr;
}