C Passing Arrays to Functions
You can pass a whole array to a function. In the function parameter we write the array name with empty brackets. We should also send the size, because the function does not know it.
Example: sum of an array
#include <stdio.h>
int sum(int arr[], int size) {
int total = 0;
for (int i = 0; i < size; i++) {
total += arr[i];
}
return total;
}
int main(void) {
int marks[] = {70, 85, 60, 95};
printf("Total = %d\n", sum(marks, 4));
return 0;
}
Output:
Output of the above program is
Total = 310
The function changes the original array
An array is not copied. The function gets the address of the first element. So if the function changes a value, the original array also changes.
#include <stdio.h>
void addBonus(int arr[], int size) {
for (int i = 0; i < size; i++) {
arr[i] += 5;
}
}
int main(void) {
int marks[] = {70, 85, 60};
addBonus(marks, 3);
for (int i = 0; i < 3; i++) {
printf("%d ", marks[i]);
}
printf("\n");
return 0;
}
Output:
Output of the above program is
75 90 65
Why sizeof does not work inside the function
Inside the function arr is only a pointer. So sizeof(arr) gives the size of a pointer, not of the array. Calculate the size in the place where the array is declared, and pass it as an argument.
Passing a 2D array
For a 2D array, the column size must be written in the parameter.
#include <stdio.h>
void show(int m[][3], int rows) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", m[i][j]);
}
printf("\n");
}
}
int main(void) {
int m[2][3] = {{1, 2, 3}, {4, 5, 6}};
show(m, 2);
return 0;
}
Output:
Output of the above program is
1 2 3
4 5 6
Note:
If the function should not change the array, write const int arr[]. Then the compiler gives an error when you try to change it.
Next: C Strings.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |