在c++中传递并返回2D阵列

passing and returning a 2D array in c++

本文关键字:返回 2D 阵列 c++      更新时间:2023-10-16

我在传入、编辑和从函数返回2D数组时遇到问题。我正在尝试使用指针来执行此操作,但无法使参数类型兼容。

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

因为2D数组和指针数组是两个不同的野兽。2D阵列只是一个序列。对于T arr[X][Y];(其中X和T是整数常数),T[i][j]根据定义是*(&(arr[0][0]) + i*Y + j)

但是对于指针数组,arr[i]就是指针,您可以编写arr[i] = new int[10];,这将导致2D数组出错。

如果你想把array[2][3](6个元素)看作array[3][2](我无法想象它的真实用例,但这正是你的代码所建议的),你可以写:

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

由于数组既不可复制也不可赋值,因此不能通过函数返回调用返回数组。

但是,您可以通过引用将数组传递到函数中。因此,将get2DArray函数更改为:

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

您可以通过引用传递任意维度的2d数组,并根据需要更改其内容实况演示

现在,如果您希望更改发生在原始阵列的副本上(例如,stuff),您可以使用std::copystuff复制到temp,然后将temp传递到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);

现场演示