Passing Two-Dimensional Arrays to Functions in C++

When passing a two-dimensional array to a function, C++ requires that the column size be specified in the function parameter type declaration.

Listing 8.1 gives an example with a function that returns the sum of all the elements in a matrix.

Listing 8.1 PassTwoDimensionalArray.cpp

1 #include <iostream>
2
using namespace std;
3
4
const int COLUMN_SIZE = 4;
5
6
int sum(const int a[][COLUMN_SIZE], int rowSize)
7 {
8   
int total = 0;
9   
for (int row = 0; row < rowSize; row++)
10   {
11     
for (int column = 0; column < COLUMN_SIZE; column++)
12      {
13         total += a

[column];
14      }
15   }
16
17   return total;
18 }
19
20
int main()
21 {
22     
const int ROW_SIZE = 3;
23     
int m[ROW_SIZE][COLUMN_SIZE];
24     cout <<
“Enter ” << ROW_SIZE << ” rows and ”
25     << COLUMN_SIZE << ” columns: ” << endl;
26     
for (int i = 0; i < ROW_SIZE; i++)
27     
for (int j = 0; j < COLUMN_SIZE; j++)
28     cin >> m[i][j];

29
30     cout <<
“\nSum of all elements is ” << sum(m, ROW_SIZE) << endl;
31
32   
return 0;
33 }

The function sum (line 6) has two arguments. The first specifies a two-dimensional array with a fixed column size. The second specifies the row size for the two-dimensional array.

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *