In C, arrays can be passed to functions to perform operations on multiple elements. Since array names act as pointers, passing an array to a function allows direct modification of its elements.
When passing an array to a function, the function receives a pointer to the first element rather than a copy of the array. This works like a call by reference and allows the function to modify the original array.
As you are passing an address to a function, the function parameter should be either declared as a pointer or
void printArray(int arr[], int size) {
for(int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
}
int main() {
int numbers[] = {1, 2, 3, 4, 5};
printArray(numbers, 5);
return 0;
}
Since arrays are passed by reference, changes made inside the function affect the original array.
void modifyArray(int arr[], int size) {
for(int i = 0; i < size; i++) {
arr[i] *= 2; // Modifies original array
}
}
int main() {
int numbers[] = {1, 2, 3, 4, 5};
modifyArray(numbers, 5);
for(int i = 0; i < 5; i++) {
printf("%d ", numbers[i]); // Output: 2 4 6 8 10
}
return 0;
}
Multidimensional arrays can also be passed to functions. The number of columns must be specified in the function parameter.
void printMatrix(int matrix[][3], int rows) {
for(int i = 0; i < rows; i++) {
for(int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\\n");
}
}
int main() {
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
printMatrix(matrix, 2);
return 0;
}