我有一个函数,我想把它作为一个参数,一个可变大小的二维数组。

到目前为止,我有这个:

void myFunction(double** myArray){
     myArray[x][y] = 5;
     etc...
}

我在代码的其他地方声明了一个数组:

double anArray[10][10];

然而,调用myFunction(anArray)会给我一个错误。

我不想在传入数组时复制它。在myFunction中所做的任何更改都应该改变anArray的状态。如果我理解正确,我只想传递一个指向2D数组的指针作为参数。该函数还需要接受不同大小的数组。比如[10][10][5][5]。我该怎么做呢?


当前回答

传递多维数组的一个重要的事情是:

第一个数组维度不需要指定。 必须指定第二个维度(任何其他维度)。

1.当全局只有第二个维度可用时(作为宏或全局常量)

const int N = 3;

void print(int arr[][N], int m)
{
int i, j;
for (i = 0; i < m; i++)
  for (j = 0; j < N; j++)
    printf("%d ", arr[i][j]);
}

int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
print(arr, 3);
return 0;
}

2.使用单个指针: 在此方法中,当传递给函数时,必须对2D数组进行类型转换。

void print(int *arr, int m, int n)
{
int i, j;
for (i = 0; i < m; i++)
  for (j = 0; j < n; j++)
    printf("%d ", *((arr+i*n) + j));
 }

int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int m = 3, n = 3;

// We can also use "print(&arr[0][0], m, n);"
print((int *)arr, m, n);
return 0;
}

其他回答

#include <iostream>

/**
 * Prints out the elements of a 2D array row by row.
 *
 * @param arr The 2D array whose elements will be printed.
 */
template <typename T, size_t rows, size_t cols>
void Print2DArray(T (&arr)[rows][cols]) {
    std::cout << '\n';
    for (size_t row = 0; row < rows; row++) {
        for (size_t col = 0; col < cols; col++) {
            std::cout << arr[row][col] << ' ';
        }
        std::cout << '\n';
    }    
}

int main()
{
    int i[2][5] = { {0, 1, 2, 3, 4},
                    {5, 6, 7, 8, 9} };
    char c[3][9] = { {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'},
                     {'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R'},
                     {'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '&'} };
    std::string s[4][4] = { {"Amelia", "Edward", "Israel", "Maddox"},
                            {"Brandi", "Fabian", "Jordan", "Norman"},
                            {"Carmen", "George", "Kelvin", "Oliver"},
                            {"Deanna", "Harvey", "Ludwig", "Philip"} };
    Print2DArray(i);
    Print2DArray(c);
    Print2DArray(s);
    std::cout <<'\n';
}

令人惊讶的是还没有人提到这一点,但是您可以简单地在任何支持[][]语义的2D上创建模板。

template <typename TwoD>
void myFunction(TwoD& myArray){
     myArray[x][y] = 5;
     etc...
}

// call with
double anArray[10][10];
myFunction(anArray);

它适用于任何2D“类数组”数据结构,例如std::vector<std::vector<T>>,或者用户定义的类型以最大限度地重用代码。

将二维数组传递给函数有三种方法:

参数为2D数组 int数组[10][10]; void passFunc(int a[][10]) { / /…… } passFunc(数组); 形参是一个包含指针的数组 int数组* [10]; For (int I = 0;I < 10;我+ +) 数组[i] = new int[10]; void passFunc(int *a[10]) //指针数组 { / /…… } passFunc(数组); 形参是指向指针的指针 int * *数组; 数组= new int *[10]; For (int I = 0;我< 10;我+ +) 数组[i] = new int[10]; void passFunc(int **a) { / /…… } passFunc(数组);

你可以使用c++中的模板功能来实现这一点。我是这样做的:

template<typename T, size_t col>
T process(T a[][col], size_t row) {
...
}

这种方法的问题在于,对于您提供的每一个col值,都会使用模板实例化一个新的函数定义。 所以,

int some_mat[3][3], another_mat[4,5];
process(some_mat, 3);
process(another_mat, 4);

实例化模板两次以生成2个函数定义(其中一个col = 3,另一个col = 5)。

尽管表面上看,double**隐含的数据结构与固定c数组(double[][])的数据结构根本不兼容。 问题是这两种方法都是C(或c++)中处理数组的流行(尽管)被误导的方法。 参见https://www.fftw.org/fftw3_doc/Dynamic-Arrays-in-C_002dThe-Wrong-Way.html

如果你不能控制代码的任何一部分,你需要一个翻译层(这里称为adapt),解释在这里:https://c-faq.com/aryptr/dynmuldimary.html

您需要生成一个指针的辅助数组,指向c数组的每一行。

#include<algorithm>
#include<cassert>
#include<vector>

void myFunction(double** myArray) {
    myArray[2][3] = 5;
}

template<std::size_t N, std::size_t M>
auto adapt(double(&Carr2D)[N][M]) {
    std::array<double*, N> ret;
    std::transform(
        std::begin(Carr2D), std::end(Carr2D),
        ret.begin(),
        [](auto&& row) { return &row[0];}
    );
    return ret;
}

int main() {
    double anArray[10][10];

    myFunction( adapt(anArray).data() );

    assert(anArray[2][3] == 5);
}

(参见工作代码:https://godbolt.org/z/7M7KPzbWY)

如果它看起来像是一场灾难,那是因为,正如我所说,这两种数据结构从根本上是不兼容的。


如果可以控制代码的两端,那么现在最好使用现代(或半现代)数组库,比如Boost。MultiArray,提振。uBLAS,特征或多。 如果数组要小,你有“小”数组库,例如在Eigen内,或者如果你不能负担任何依赖,你可以尝试简单的std::array<std::array<double, N>, M>。

使用Multi,你可以简单地这样做:

#include<multi/array.hpp>

#include<cassert>

namespace multi = boost::multi;

template<class Array2D>
void myFunction(Array2D&& myArray) {
    myArray[2][3] = 5;
}

int main() {
    multi::array<double, 2> anArray({10, 10});

    myFunction(anArray);

    assert(anArray[2][3] == 5);
}

(工作代码:https://godbolt.org/z/7M7KPzbWY)