Passing an array to function in the one-Dimensional array is done through an actual parameter and array variables with subscript are passed as formal arguments. While passing array only the name of the array is passed to the function.
Same method is applied for the multi-dimensional array.
There are three methods that can be used to pass an array to a function.
First Way: As a unsized array
1 2 3 4 | return_type function(type arrayname[]) { ..... } |
Second Way: As a sized array
1 2 3 4 | return_type function(type arrayname[SIZE]) { ..... } |
Third Way: As a pointer
1 2 3 4 | return_type function(type *arrayname) { ..... } |
Example: Passing a One-Dimensional Array in Function in C
To find the average of given number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #include <stdio.h> float avgresult(float age[]); int main() { float avg, score[] = { 14.4, 23, 19.6, 9, 56.9, 18 }; avg = avgresult(score); // Only name of an array is passed as an argument printf("Average Score = %.2f", avg); return 0; } //function float avgresult(float score[]) { int i; float avg, sum = 0.0; for (i = 0; i < 6; ++i) { sum += score[i]; } avg = (sum / 6); return avg; } |
Output:
1 | Average Score = 23.48 |
Example: Passing a Multi-Dimensional Array in Function in C
Program takes an input from the user and a function is used to display the array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #include <stdio.h> void displayArray(int arr[3][2]); int main() { int arr[3][2]; printf("Enter 6 numbers for an array:\n"); for (int i = 0; i < 3; ++i) for (int j = 0; j < 2; ++j) scanf("%d", &arr[i][j]); // passing multi-dimensional array to a function displayArray(arr); return 0; } void displayArray(int arr[3][2]) { printf("Displaying the Entered Number: \n"); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 2; ++j) { printf("%d\n", arr[i][j]); } } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | Enter 6 numbers for an array: 56 22 67 88 2 8 Displaying the Entered Number: 56 22 67 88 2 8 |