C++二维数组作为函数参数

二维数组传递给函数时,形参类型必须包含数的大小声明符,C++ 需要这些信息才能正确地将下标数组引用(如 table[2][1])转换为存列储该元素的内存地址。

下面的程序演示了如何将一个二维数组传递给一个函数。以下是程序中函数 showArmy 的头文件:

void showArray(const int array [][NUM_COLS], int numRows)

showArray 函数可以接受任何二维整数数组,只要它有 4 列。在程序中,这个函数显示了两个独立数组的内容。
  1. // This program demonstrates how to pass
  2. // a two-dimensional array to a function.
  3. #include <iostream>
  4. #include <iomanip>
  5. using namespace std;
  6.  
  7. const int NUM_COLS = 4; // Number of columns in each array
  8. const int TBL1_R0WS = 3; // Number of rows in table1
  9. const int TBL2_R0WS = 4; // Number of rows in table2
  10.  
  11. void showArray(const int [][NUM_COLS], int); // Function prototype
  12.  
  13. int main()
  14. {
  15. int table1[TBL1_R0WS][NUM_COLS] = {{1, 2, 3, 4},{5, 6, 7, 8},{9, 10, 11, 12} };
  16. int table2[TBL2_R0WS][NUM_COLS] = {{ 10, 20, 30, 40},{ 50, 60, 70, 80},{ 90, 100, 110, 120},{130, 140, 150, 160} };
  17. cout << "The contents of table1 are:\n";
  18. showArray(table1, TBL1_R0WS);
  19. cout << "\nThe contents of table2 are:\n";
  20. showArray(table2, TBL2_R0WS);
  21. return 0;
  22. }
  23. void showArray(int const array[][NUM_COLS], int numRows)
  24. {
  25. for (int row = 0; row < numRows; row++)
  26. {
  27. for (int col = 0; col < NUM_COLS; col++)
  28. {
  29. cout << setw (5) << array[row][col] << " ";
  30. }
  31. cout << endl;
  32. }
  33. }
程序输出结果:

The contents of table1 are:
    1     2     3     4
    5     6     7     8
    9    10    11    12

The contents of table2 are:
   10    20    30    40
   50    60    70    80
   90   100   110   120
  130   140   150   160

由于二维数组存储在内存中,所以 C++ 要求在函数原型和函数头中指定列。一行实际上跟在另一行之后,如图 1 所示。

二维数组在内存中的位置示意图
图 1 二维数组在内存中的位置示意图

当编译器生成访问二维数组元素的代码时,需要知道行在内存中按多少个字节分隔开来,因此,列数是这个计算中的关键因素。

这个必要的列信息也可以用一个 typedef 声明来提供。以下是一个二维数组的 typedef 声明看起来的样子:

typedef int intTable [][4];

该语句使 intTable 成为具有任意行数和 4 列的二维数组的别名。如果这个 typedef 语句已经包含在此程序中,那么 showArray 函数的原型就可以写成如下形式:

void showArray(intTable, int);

其函数头则可以写成以下形式:

void showArray(intTable array, int numRows)