
下面的程序演示了如何将一个二维数组传递给一个函数。以下是程序中函数 showArmy 的头文件:
voID showArray(const int array [][NUM_ColS],int numRows)
showArray 函数可以接受任何二维整数数组,只要它有 4 列。在程序中,这个函数显示了两个独立数组的内容。// This program demonstrates how to pass// a two-dimensional array to a function.#include <iostream>#include <iomanip>using namespace std;const int NUM_ColS = 4; // Number of columns in each arrayconst int TBL1_R0WS = 3; // Number of rows in table1const int TBL2_R0WS = 4; // Number of rows in table2voID showArray(const int [][NUM_ColS],int); // Function prototypeint main(){ int table1[TBL1_R0WS][NUM_ColS] = {{1,2,3,4},{5,6,7,8},{9,10,11,12} }; int table2[TBL2_R0WS][NUM_ColS] = {{ 10,20,30,40},{ 50,60,70,80},{ 90,100,110,120},{130,140,150,160} }; cout << "The contents of table1 are:\n"; showArray(table1,TBL1_R0WS); cout << "\nThe contents of table2 are:\n"; showArray(table2,TBL2_R0WS); return 0;}voID showArray(int const array[][NUM_ColS],int numRows){ for (int row = 0; row < numRows; row++) { for (int col = 0; col < NUM_ColS; coL++) { cout << setw (5) << array[row][col] << " "; } cout << endl; }}程序输出结果: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
图 1 二维数组在内存中的位置示意图
当编译器生成访问二维数组元素的代码时,需要知道行在内存中按多少个字节分隔开来,因此,列数是这个计算中的关键因素。
这个必要的列信息也可以用一个 typedef 声明来提供。以下是一个二维数组的 typedef 声明看起来的样子:
typedef int inttable [][4];
该语句使 inttable 成为具有任意行数和 4 列的二维数组的别名。如果这个 typedef 语句已经包含在此程序中,那么 showArray 函数的原型就可以写成如下形式:voID showArray(inttable,int);
其函数头则可以写成以下形式:voID showArray(inttable array,int numRows)
总结以上是内存溢出为你收集整理的C++二维数组作为函数参数全部内容,希望文章能够帮你解决C++二维数组作为函数参数所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)