C/C++二维数组参数传递

C/C++语言中二维数组参数传递常用三种方法:

  • 方法一:形参为二维数组并给出第二维的大小

    如:void sum(int a[][3])

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    #include<iostream>
    using namespace std;
    void sum(int a[][3])
    {
    int s = 0;
    for (int j = 0; j < 3; j++)
    {
    s += a[0][j];
    }
    cout << s << endl;
    }
    int main()
    {
    int b[2][3] = { {1,2,3},{4,5,6} };
    sum(b);
    return 0;
    }
  • 方法二:形参为指向数组的指针并给出数组的长度

    如:void sum(int (*a)[3])

    1
    2
    3
    4
    5
    6
    7
    8
    9
    void sum1(int(*a)[3])
    {
    int s = 0;
    for (int j = 0; j < 3; j++)
    {
    s += a[0][j];
    }
    cout << s << endl;
    }
  • 方法三:形参为指针的指针且实参必须为指针,而不能是数组名

    如:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    #include<iostream>
    using namespace std;
    void sum(int **a)
    {
    int s = 0;
    for (int j = 0; j < 3; j++)
    {
    s += a[0][j];
    }
    cout << s << endl;
    }

    int main()
    {
    int *a[2];
    int b[2][3] = { {1,2,3},{4,5,6} };
    a[0] = b[0];
    a[1] = b[1];
    sum(a);
    return 0;
    }
Author: wnxy
Link: https://wnxy.github.io/2020/05/01/C-or-C++_two-dimensional-array-parameter-transfer/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.