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 array const int TBL1_R0WS = 3; // Number of rows in table1 const int TBL2_R0WS = 4; // Number of rows in table2 void showArray(const int [][NUM_COLS], int); // Function prototype int 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