In the C programming language, arrays are a fundamental data structure that allows you to store multiple values of the same data type. When working with arrays, you may often come across situations where you need to pass an array to a function. This can be done in C by using pointers.
To pass an array to a function in C, you can use either of the following methods:
1. Pass by reference:
In this method, you pass the address of the array to the function. The function then accesses the array elements using pointers. This method allows the function to modify the original array.
Here’s an example of passing an array to a function using pass by reference:
“`c
void modifyArray(int* arr, int size) {
for(int i = 0; i < size; i++) {
arr[i] *= 2; // double each element
}
}
int main() {
int myArray[] = {1, 2, 3, 4, 5};
int size = sizeof(myArray) / sizeof(myArray[0]);
modifyArray(myArray, size);
// Print modified array
for(int i = 0; i < size; i++) {
printf(“%d “, myArray[i]);
}
return 0;
}
“`
Output:
“`
2 4 6 8 10
“`
In the above example, the `modifyArray` function takes a pointer to an integer (`int*`) and the size of the array as arguments. It then iterates over the array elements using pointers and doubles each element.
2. Pass by value:
In this method, you pass the array itself to the function. However, since arrays are passed by value, any modifications made to the array within the function will not affect the original array.
Here’s an example of passing an array to a function using pass by value:
“`c
void printArray(int arr[], int size) {
for(int i = 0; i < size; i++) {
printf(“%d “, arr[i]);
}
}
int main() {
int myArray[] = {1, 2, 3, 4, 5};
int size = sizeof(myArray) / sizeof(myArray[0]);
printArray(myArray, size);
return 0;
}
“`
Output:
“`
1 2 3 4 5
“`
In the above example, the `printArray` function takes an array of integers and the size of the array as arguments. It then simply prints the elements of the array.
It’s important to note that when passing an array to a function in C, the size of the array should also be passed as an argument. This is because arrays in C do not carry their size information with them.
In conclusion, passing an array to a function in C can be done either by passing the address of the array (pass by reference) or by passing the array itself (pass by value). Depending on your requirements, you can choose the appropriate method.