passing and returning a 2D array in c++

时间:2015-10-30 21:38:26

标签: c++ arrays

I am having trouble passing in, editing, and then returning a 2D array from a function. I am trying using a pointer to do so, but cannot get the parameter types to be compatible.

#include <iostream>

using namespace std;

double** get2DArray(double *info[3])
{
    for(int i = 0; i < 3; i++)
        for(int j = 0; j < 2; j++)
            if(i == j)
                info[i][j] = 0;

    double** out = info;
    return out;
}

int main()
{
    double stuff[2][3] = {{1, 3, 5},{2, 4, 6}};
    double(*temp)[3] = stuff;

    double** info = get2DArray(temp);

    for(int i = 0; i < 3; i++)
        for(int j = 0; j < 2; j++)
            cout << info[i][j] << endl;

    return 0;
}

2 个答案:

答案 0 :(得分:0)

Because a 2D array and an array of pointers are two different beasts. A 2D array is just a single sequence. With T arr[X][Y]; (where X and T are integer constants) T[i][j] is by definition *(&(arr[0][0]) + i*Y + j).

But with an array of pointers arr[i] is a pointer, and you can write arr[i] = new int[10]; which would cause an error with a 2D array.

If you want to see an array[2][3] (6 elements) as an array[3][2] (I cannot imagine a real use case for it, but it is what your code suggests), you could write:

#include <iostream>

using namespace std;

double  (*get2DArray(double (*info)[2][3]))[2][3]
{
    for(int i = 0; i < 3; i++)
        for(int j = 0; j < 2; j++)
            if(i == j)
                (*info)[i][j] = 0;

    double (* out)[2][3] = info;
    return out;
}

int main()
{
    double stuff[2][3] = {{1, 3, 5},{2, 4, 6}};
    double (*temp)[2][3] = &stuff;

    double (*info)[3][2] = reinterpret_cast<double (*)[3][2]>(get2DArray(temp));

    for(int i = 0; i < 3; i++)
        for(int j = 0; j < 2; j++)
            cout << (*info)[i][j] << endl;

    return 0;
}

答案 1 :(得分:0)

You can't return an array through a function return call, due to the fact that arrays are not copyable nor are assignable.

However, you can pass an array into a function by reference. Hence, changing your get2DArray function to:

template<std::size_t N, std::size_t M>
void get2DArray(double (&info)[N][M]) {
  // ...
} 

You can pass an arbitrary dimensions 2d array by reference and change its contents as desired LIVE DEMO.

Now if you want the change to take place on a copy of your original array (e.g., stuff), you could copy stuff into temp using std::copy and then pass temp to get2DArray:

double stuff[2][3] = {{1, 3, 5},{2, 4, 6}};
double temp[2][3];
std::copy(&stuff[0][0], &stuff[0][0] + 6, &temp[0][0]);
get2DArray(temp);

LIVE DEMO