English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, you will learn how to pass arrays (one-dimensional and multidimensional arrays) to functions in C language programming through examples.
In C language programming, you can pass the entire array to a function. Before understanding this, let's see how to pass individual elements of an array to a function.
Passing an array element to a function is similar toPassing a variable to a function.
#include <stdio.h> void display(int age1, int age2) { printf("%d\n", age1}); printf("%d\n", age2}); } int main() { int ageArray[] = {2, 8, 4, 12}; //Passing the second and third elements to display() display(ageArray[1], ageArray[2]); return 0; }
Output Result
8 4
//The program calculates the sum of array elements by passing them to a function #include <stdio.h> float calculateSum(float age[]); int main() { float result, age[] = {23.4, 55, 22.6, 3, 40.5, 18}; //Passing the age array to calculateSum() result = calculateSum(age); printf("Result = %.2f", result); return 0; } float calculateSum(float age[]) { float sum = 0.0; for (int i = 0; i < 6; ++i) {}} sum += age[i]; } return sum; }
Output Result
Result = 162.50
To pass the entire array to a function, pass only the array name as a parameter.
result = calculateSum(age);
But, please note the use of [] in the function definition.
float calculateSum(float age[]) { ... .. }
This informs the compiler that you are passing a one-dimensional array to the function.
To pass a multidimensional array to a function, only pass the name of the array to the function (similar to a one-dimensional array).
#include <stdio.h> void displayNumbers(int num[2][2]); int main() { int num[2][2]); printf("Input ",4a number:\n"); for (int i = 0; i < 2; ++i) for (int j = 0; j < 2; ++j) scanf("%d", &num[i][j]); //Passing a multidimensional array to a function displayNumbers(num); return 0; } void displayNumbers(int num[2][2]) { printf("Displaying:\n"); for (int i = 0; i < 2; ++i) {}} for (int j = 0; j < 2; ++j) { printf("%d\n", num[i][j]); } } }
Output Result
Input4number of digits: 2 3 4 5 Displaying: 2 3 4 5
Note:In C language programming, arrays can be passed to functions, but arrays cannot be returned from functions.