Easy tutorial for C / C ++ - Arrays 8 (Passing a
two-dimensional array as an argument to a function)
-
Let's take a look at passing a two-dimensional array as an argument to a
function.
-
In a one-dimensional array, we passed the array name which represents the
starting address of the array. Two-dimensional arrays are similar, but take a
slightly different approach.
-
Let's look at an example.
Example Code
#include
<iostream>
#include
<iomanip>
using
namespace std;
void
test2DA (int (*ptA)[3] );
int
main() {
int a[2][3] = { {0,1,2},
{3,4,5} };
for(int i = 0; i < 2; i++){
for(int j = 0; j < 3; j++){
cout << setw(15) << a[i][j] ;
}
cout << endl;
}
cout << endl;
test2DA (a);
return 0;
}
void
test2DA(int (*ptA)[3]){
cout
<< " Results of function \'test2DA\' " << endl;
for(int
i = 0; i < 2; i++){
for(int j = 0; j < 3; j++){
cout << setw(15) << *(*( ptA + i) + j) ;
}
cout << endl;
}
cout << endl;
}
-
We first declared an output function called 'test2DA'. To use a two-dimensional
array as a function argument, we write the argument as follow.
void
test2DA (int (*ptA)[3] );
-
'ptA' is a two-dimensional pointer variable, followed by [3] is the number of
two-dimensional array columns. That is, the number of columns contained in a
row.
-
I made the output once in the main function and then the 'test2DA' function.
-
In definition section of the function 'test2DA', we have created a statement
that takes the starting address value of the 2D array and prints it.
-
If you run it, you will get the following results.
results
:
0 1 2
3 4 5
Results of function 'test2DA'
0 1 2
3 4 5
note)
-
In the definition section of the function 'test2DA',
*
(* (ptA + i) + j) can be substituted to a two-dimensional array of ptA[i][j]
-
You can see that it is executed even if you change the argument part of
function declaration part and definition part as follows.
(*ptA)[3] --->
ptA[][3]
- Where
'ptA' represents a two-dimensional pointer variable.
No comments:
Post a Comment