Passing array to function
In C, when we pass an array to a function, we’re actually passing a pointer to the first element of the array, not a copy of the entire array. This is efficient because it avoids copying the whole array, which can be slow if the array is large. Let’s go step-by-step to understand how this works.
Key Concepts
- Array Decay: When an array is passed to a function, it “decays” to a pointer to its first element. This means the function receives the memory address of the first element, not the entire array.
- Modifying Original Array: Since the function has a pointer to the original array, any changes made to the array elements within the function affect the original array.
Example: Passing an Array to a Function
#include <stdio.h>
void multiplyArray(int arr[], int size, int multiplier) {
for (int i = 0; i < size; i++) {
arr[i] *= multiplier; // Multiply each element by the multiplier
}
}
int main() {
int numbers[] = {1, 2, 3, 4, 5};
int length = sizeof(numbers) / sizeof(numbers[0]);
printf("Original array:\n");
for (int i = 0; i < length; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
// Multiply each element by 2
multiplyArray(numbers, length, 2);
printf("Modified array after multiplying by 2:\n");
for (int i = 0; i < length; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
return 0;
}
Explanation:
- Function Definition:
multiplyArray
takes an array, its size, and a multiplier. Inside the function, we modify each element ofarr
by multiplying it by the multiplier. - Directly Modifying Original Array: Since
arr
is a pointer tonumbers
, modifyingarr[i]
directly affectsnumbers[i]
inmain
.
Key Takeaways
- Array Decays to Pointer: When passing an array to a function, only the pointer to the first element is passed, not the entire array.
- Direct Access to Original Array: Modifications made to the array elements inside the function affect the original array in the calling function.
This approach is efficient and flexible, allowing functions to operate on arrays without copying them.
Comments
Post a Comment