As we know that an array is a collection same kind of data in a contiguous memory location but can we pass the array data as an argument to a function? The answer to this question is no. We cannot pass the entire array as an argument to a function but we can pass a pointer to an array.
We have totally different methods for passing a one-dimensional and two-dimensional array to a function in C++. Let's discuss both of them one by one:
Passing One-Dimensional Array to Function.
//C++ Example to show ways of Passing Array to Function #include<iostream> using namespace std;
//Formal parameter as unsized array
void funType1(int arr[], int n){
int size = sizeof(arr)/sizeof(arr[0]);
cout<<"\nSize of array inside fun1: "<<size<<endl;
arr[2] = 10;
cout<<"Array Elements in fun1: ";
for(int i = 0; i < n; i++)
cout<<arr[i]<<" ";
}
//Formal parameter as a pointer
void funType2(int *arr, int n){ int size = sizeof(arr)/sizeof(arr[0]); cout<<"Size of array inside fun2: "<<size<<endl; arr[n-1] = 23; cout<<"Array Elements in fun2: "; for(int i = 0; i < n; i++) cout<<arr[i]<<" "; } int main(){ int arr[] = {3, 4, 5, 7, 8, 9}; //size of array int n = sizeof(arr)/sizeof(arr[0]); cout<<"Size of given array: "<<n<<endl; cout<<"Array Elements: "; for(int i = 0; i < n; i++) cout<<arr[i]<<" ";
//function 1 call
funType1(arr, n); cout<<endl;
//function 2 call
funType2(arr, n);
return 0;
}
Size of given array: 6
Array Elements: 3 4 5 7 8 9
Size of array inside fun1: 2
Array Elements in fun1: 3 4 10 7 8 9
Size of array inside fun2: 2
Array Elements in fun2: 3 4 10 7 8 23
- The first is passing an unsized array as a parameter. (syntax: fun(int arr[]))
- The second is passing as a pointer. (syntax: fun(int *arr))
Passing Two-Dimensional Array to Function.
//C++ Example code for passing 2D array to function #include<iostream> using namespace std; //Passing matrix to a function void fun2DArray(int arr[][3], int r, int c){ cout<<"Elements of 2D Array: "<<endl; for(int i = 0; i < r; i++){ for(int j = 0; j < c; j++){ cout<<arr[i][j]<<" "; } cout<<endl; } } int main(){ int arr[][3] = {{2, 3, 7},{9, 5, 1},{4, 6, 2}}; int row = sizeof(arr)/sizeof(arr[0]); int col = sizeof(arr[0])/sizeof(arr[0][0]); fun2DArray(arr, row, col); return 0; }
Elements of 2D Array:
2 3 7
9 5 1
4 6 2
No comments:
Post a Comment