How to pass a two-dimensional array as a parameter in C++?

There are several ways to pass a 2D array in C++. Here are some common methods:

  1. “pointer to a pointer”
void function(int** arr, int rows, int cols) {
    // 使用arr访问二维数组的元素
}

int main() {
    int rows = 3;
    int cols = 4;
    int** arr = new int*[rows];
    for (int i = 0; i < rows; ++i) {
        arr[i] = new int[cols];
    }
    // 初始化二维数组的值
    
    function(arr, rows, cols);
    
    // 释放内存
    for (int i = 0; i < rows; ++i) {
        delete[] arr[i];
    }
    delete[] arr;
    
    return 0;
}
  1. arr is a reference to a 2D array with rows and cols dimensions.
void function(int (&arr)[3][4]) {
    // 使用arr访问二维数组的元素
}

int main() {
    int arr[3][4];
    // 初始化二维数组的值

    function(arr);
    
    return 0;
}
  1. Template parameters can be used to pass a two-dimensional array. An example code is shown below:
template<size_t rows, size_t cols>
void function(int (&arr)[rows][cols]) {
    // 使用arr访问二维数组的元素
}

int main() {
    int arr[3][4];
    // 初始化二维数组的值

    function(arr);
    
    return 0;
}

All these methods can be used to pass a two-dimensional array to a function, the specific method chosen depends on your needs and preferences.

bannerAds