YouTip LogoYouTip

C Passing Arrays To Functions

# C Passing Arrays to Functions [![Image 3: C Arrays](#) C Arrays](#) 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. All three ways produce the same result, as each 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 (you can learn about pointers in the next chapter): void myFunction(int *param){ . . . } ### Method 2 The formal parameter is a sized array: void myFunction(int param){ . . . } ### Method 3 The formal parameter is an unsized 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; double avg; double sum; for(i = 0; i<size; ++i){sum += arr; }avg = sum / size; return avg; } Now, let's call the above function as shown below: ## Example #include/* 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 */printf("Average is: %f ", avg); return 0; }double getAverage(int arr[], int size){int i; double avg; double sum=0; for(i = 0; i<size; ++i){sum += arr; }avg = sum / size; return avg; } When the above code is compiled and executed, it produces the following result: Average is: 214.400000 You can see that, as far as the function is concerned, the length of the array is irrelevant, because C does not perform boundary checking on formal parameters. [![Image 4: C Arrays](#) C Arrays](#)
← C Pointer To An ArrayLinux Comm Passwd β†’