如何将poiner转换为2维数组到f

时间:2016-11-23 13:21:05

标签: c++ pointers

我正在开发一个转置数组的函数(即a [i] [j] => a [j] [i])。 要测试该函数,将创建以下数组:array [4] [3] = {...} 但是编译器会返回错误:

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) ===|

据我所知,array的类型为int**。那么,transpose函数怎么能占用这个数组?

#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;
}

2 个答案:

答案 0 :(得分:0)

您可以将reinterpret_cast数组重命名为(int *)或使用模板函数。

... = transpose(reinterpret_cast<int *>(array),...);

并且在转置中,你必须使用m作为一维数组,自己计算actul索引:array [i] [j]变为m [i * cols + j]。

或声明转置为

template <size_t kRows, size_t kCols>
... transpose(const int (&m)[kRows][kCols]) {
  //you may use kCols and kRows as const variables, and use m as a 2D array
}

致电:

... = transpose(array);

答案 1 :(得分:0)

如果你已经传递了一个2d数组来运行并像arr [i] [j]一样使用它。然后,您应该使用动态分配创建所有数组并将双指针传递给function.Your代码应该看起来像

#include <iostream>
#include <cstdlib>

using namespace std;

int** create_array( int r, int c ){
    int** arr = new int*[r];
    for( int i=0; i<r; i++ ){
        arr[i] = new int[c];
    }
    return arr;
}

void delete_array( int** arr, int r){
    for( int i=0; i<r; i++ ) delete [] arr[i];
    delete [] arr;
}

int** transpose(int** arr, int r, int c)
{

  int **tr = create_array( c, r );
  for (int i = 0; i<c; i++){
    for (int j = 0; j < r; j++) {
      tr[i][j] = arr[j][i];
    }
  }
  return tr;
}


int main()
{   int r = 4, c = 3, cnt=0;
    int** m = create_array( r, c );
    for( int i=0; i<r; i++ )
        for( int j=0; j<c; j++ )
            m[i][j] = ++cnt;
    int** tr = transpose(m,r,c);

    for( int i=0;i<c; i++){
        for( int j=0;j <r; j++ )
            cout << tr[i][j] << " ";
        cout << endl;
    }

    delete_array(m,r);   // dont forget to delete dynamic allocated mem
    delete_array(tr,c);  // dont forget to delete dynamic allocated mem
    return 0;
}