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

到目前为止,我有这个:

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

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

double anArray[10][10];

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

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


当前回答

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

其他回答

如果你想将int的[2][3]传递给void func(int** pp),你需要以下辅助步骤。

int a[2][3];
int* p[2] = {a[0],a[1]};
int** pp = p;

func(pp);

由于第一个[2]可以隐式指定,因此可以进一步简化为。

int a[][3];
int* p[] = {a[0],a[1]};
int** pp = p;

func(pp);

一维数组衰减为指向数组中第一个元素的指针。而2D数组则衰减为指向第一行的指针。所以,函数原型应该是-

void myFunction(double (*myArray) [10]);

我更喜欢std::vector而不是原始数组。

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

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

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

你可以像这样创建一个函数模板:

template<int R, int C>
void myFunction(double (&myArray)[R][C])
{
    myArray[x][y] = 5;
    etc...
}

然后你通过R和c有两个维度大小,每个数组大小都会创建一个不同的函数,所以如果你的函数很大,并且你用各种不同的数组大小调用它,这可能代价很高。你可以像这样使用它作为一个函数的包装器:

void myFunction(double * arr, int R, int C)
{
    arr[x * C + y] = 5;
    etc...
}

它将数组视为一维,并使用算术计算出索引的偏移量。在这种情况下,你可以这样定义模板:

template<int C, int R>
void myFunction(double (&myArray)[R][C])
{
    myFunction(*myArray, R, C);
}

固定大小

1. 通过引用传递

template <size_t rows, size_t cols>
void process_2d_array_template(int (&array)[rows][cols])
{
    std::cout << __func__ << std::endl;
    for (size_t i = 0; i < rows; ++i)
    {
        std::cout << i << ": ";
        for (size_t j = 0; j < cols; ++j)
            std::cout << array[i][j] << '\t';
        std::cout << std::endl;
    }
}

在c++中,通过引用传递数组而不丢失维度信息可能是最安全的,因为不需要担心调用者传递不正确的维度(当不匹配时编译器会标记)。然而,这对于动态(独立式)数组是不可能的;它只适用于自动(通常是栈生存的)数组,即维度应该在编译时知道。

2. 传递指针

void process_2d_array_pointer(int (*array)[5][10])
{
    std::cout << __func__ << std::endl;
    for (size_t i = 0; i < 5; ++i)
    {
        std::cout << i << ": ";
        for (size_t j = 0; j < 10; ++j)
            std::cout << (*array)[i][j] << '\t';
        std::cout << std::endl;
    }    
}

The C equivalent of the previous method is passing the array by pointer. This should not be confused with passing by the array's decayed pointer type (3), which is the common, popular method, albeit less safe than this one but more flexible. Like (1), use this method when all the dimensions of the array is fixed and known at compile-time. Note that when calling the function the array's address should be passed process_2d_array_pointer(&a) and not the address of the first element by decay process_2d_array_pointer(a).

变量的大小

这些维继承自C语言,但不太安全,编译器没有办法检查,确保调用者传递了所需的维。该函数仅依赖调用者传入的维度。它们比上面的更灵活,因为不同长度的数组可以不变地传递给它们。

需要记住的是,在C中没有直接将数组传递给函数这样的事情[而在c++中,它们可以作为引用传递(1)];(2)将指针传递给数组,而不是数组本身。始终按原样传递数组成为一个指针复制操作,这得益于数组衰减为指针的特性。

3.传递一个指向衰减类型的指针(value)

// int array[][10] is just fancy notation for the same thing
void process_2d_array(int (*array)[10], size_t rows)
{
    std::cout << __func__ << std::endl;
    for (size_t i = 0; i < rows; ++i)
    {
        std::cout << i << ": ";
        for (size_t j = 0; j < 10; ++j)
            std::cout << array[i][j] << '\t';
        std::cout << std::endl;
    }
}

Although int array[][10] is allowed, I'd not recommend it over the above syntax since the above syntax makes it clear that the identifier array is a single pointer to an array of 10 integers, while this syntax looks like it's a 2D array but is the same pointer to an array of 10 integers. Here we know the number of elements in a single row (i.e. the column size, 10 here) but the number of rows is unknown and hence to be passed as an argument. In this case there's some safety since the compiler can flag when a pointer to an array with second dimension not equal to 10 is passed. The first dimension is the varying part and can be omitted. See here for the rationale on why only the first dimension is allowed to be omitted.

4. 将一个指针传递给另一个指针

// int *array[10] is just fancy notation for the same thing
void process_pointer_2_pointer(int **array, size_t rows, size_t cols)
{
    std::cout << __func__ << std::endl;
    for (size_t i = 0; i < rows; ++i)
    {
        std::cout << i << ": ";
        for (size_t j = 0; j < cols; ++j)
            std::cout << array[i][j] << '\t';
        std::cout << std::endl;
    }
}

Again there's an alternative syntax of int *array[10] which is the same as int **array. In this syntax the [10] is ignored as it decays into a pointer thereby becoming int **array. Perhaps it is just a cue to the caller that the passed array should have at least 10 columns, even then row count is required. In any case the compiler doesn't flag for any length/size violations (it only checks if the type passed is a pointer to pointer), hence requiring both row and column counts as parameter makes sense here.

Note: (4) is the least safest option since it hardly has any type check and the most inconvenient. One cannot legitimately pass a 2D array to this function; C-FAQ condemns the usual workaround of doing int x[5][10]; process_pointer_2_pointer((int**)&x[0][0], 5, 10); as it may potentially lead to undefined behaviour due to array flattening. The right way of passing an array in this method brings us to the inconvenient part i.e. we need an additional (surrogate) array of pointers with each of its element pointing to the respective row of the actual, to-be-passed array; this surrogate is then passed to the function (see below); all this for getting the same job done as the above methods which are more safer, cleaner and perhaps faster.

下面是一个测试上述功能的驱动程序:

#include <iostream>

// copy above functions here

int main()
{
    int a[5][10] = { { } };
    process_2d_array_template(a);
    process_2d_array_pointer(&a);    // <-- notice the unusual usage of addressof (&) operator on an array
    process_2d_array(a, 5);
    // works since a's first dimension decays into a pointer thereby becoming int (*)[10]

    int *b[5];  // surrogate
    for (size_t i = 0; i < 5; ++i)
    {
        b[i] = a[i];
    }
    // another popular way to define b: here the 2D arrays dims may be non-const, runtime var
    // int **b = new int*[5];
    // for (size_t i = 0; i < 5; ++i) b[i] = new int[10];
    process_pointer_2_pointer(b, 5, 10);
    // process_2d_array(b, 5);
    // doesn't work since b's first dimension decays into a pointer thereby becoming int**
}