passing an array to a function
Passing an Array to a Function in C
To pass an array to a function in C, you can use either of the following methods:
- Pass the array as a pointer:
- In this method, you pass the base address of the array to the function.
- The function receives the array as a pointer parameter and can access the array elements using pointer arithmetic.
- Any modifications made to the array elements within the function will affect the original array.
- Here is an example:
```c void modifyArray(int arr, int size) { for (int i = 0; i < size; i++) { arr[i] = 2; // Multiply each element by 2 } }
int main() { int arr[] = {1, 2, 3, 4, 5}; int size = sizeof(arr) / sizeof(arr[0]);
modifyArray(arr, size);
// Print modified array
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
return 0;
} ```
Output:
2 4 6 8 10
- Pass the array as a sized array:
- In this method, you pass the entire array to the function as a parameter.
- The function receives the array as a sized array parameter, which preserves the size information of the array.
- The function can access the array elements using array indexing.
- Any modifications made to the array elements within the function will affect the original array.
- Here is an example:
```c void modifyArray(int arr[], int size) { for (int i = 0; i < size; i++) { arr[i] *= 2; // Multiply each element by 2 } }
int main() { int arr[] = {1, 2, 3, 4, 5}; int size = sizeof(arr) / sizeof(arr[0]);
modifyArray(arr, size);
// Print modified array
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
return 0;
} ```
Output:
2 4 6 8 10
These methods allow you to pass an array to a function in C and modify its elements within the function. Remember to pass the size of the array along with the array itself to ensure proper array access and manipulation.