YouTip LogoYouTip

Cpp Passing Arrays To Functions

# C++ Passing Arrays to Functions [![Image 3: C++ Arrays](#) C++ Arrays](#) In C++, you can pass a pointer to an array by specifying the array name without an index. When passing an array to a function in C++, the array type is automatically converted to a pointer type, so what is actually passed is the address. If you want to pass a one-dimensional array as a parameter to a function, you must declare the function's formal parameter in one of the following three ways, and the result of these three declarations is the same, as each way tells the compiler that it will receive an integer pointer. Similarly, you can also pass a multi-dimensional array as a formal parameter. ### Method 1 The formal parameter is a pointer: void myFunction(int *param){...} ### Method 2 The formal parameter is a defined-size array: void myFunction(int param){...} ### Method 3 The formal parameter is an undefined-size array: void myFunction(int param[]){...} ## Example Now, let's look at the following function, which takes an array as a parameter and also passes another parameter. Based on the passed parameters, it returns the average value of the elements in the array: double getAverage(int arr[], int size){int i, sum = 0; double avg; for(i = 0; i<size; ++i){sum += arr; }avg = double(sum) / size; return avg; } Now, let's call the above function as shown below: ## Example #includeusing namespace std; // Function declaration double getAverage(int arr[], int size); int main(){// Integer array with 5 elements int balance = {1000, 2, 3, 17, 50}; double avg; // Pass a pointer to the array as a parameter avg = getAverage(balance, 5) ; // Output the returned value cout<<"Average value is: "<<avg<<endl; return 0; } When the above code is compiled and executed, it produces the following result: Average value is: 204.4
← C Function MblenEclipse Code Templates β†’