When a pointer or array is passed to a function in C, a copy of the pointer value (i.e., the memory address) is actually passed, not the array itself or its memory contents. Historically, arrays in C are not passed by value - instead, a pointer to the first element of the array is sent to the function. This mechanism saves memory but can lead to unwanted side effects when used incorrectly.
Problem - confusion between pointers and arrays: developers often believe that the external array cannot be modified within the function or that the function automatically knows the size of the passed array. In practice, the function loses the original size of the array and can easily go out of its bounds.
Solution - always explicitly pass the size of the array as a separate argument, clearly understand the difference between a copy of the pointer and a copy of the object, and remember that any changes made via the pointer reflect on the original data.
Example of correct array passing:
void print_array(const int* arr, size_t size) { for (size_t i = 0; i < size; ++i) printf("%d ", arr[i]); } int main() { int nums[] = {1,2,3,4,5}; print_array(nums, sizeof(nums)/sizeof(nums[0])); return 0; }
Key features:
Can a function determine the length of the passed array if it was declared as int arr[10]?
Answer: No, within the function, the expression sizeof(arr) will return the size of the pointer, not the entire array. The size must be passed separately.
Is passing the array as int arr[] and as int arr in functions the same?*
Answer: Yes, in the function signature this is equivalent - in both cases, a pointer to int is passed. There are only syntax differences.
If the elements of the array are modified within the function, will the original array change?
Answer: Yes, because a pointer is passed, the function modifies the memory it points to.
The project implemented an array initialization function, determining the size within the function using sizeof(arr) / sizeof(arr[0]). During testing, the function worked, but when processing other arrays, it corrupted memory or worked incorrectly.
Pros:
Cons:
The function always accepted the size of the array as a separate parameter, with the length calculated by the calling party. Inside the function, only the passed parameters were being worked with.
Pros:
Cons: