In C, arrays are not passed to functions by value. When an array is passed as an argument, a pointer to the first element of the array is actually passed to the function. This leads to the function modifying the original array rather than a copy of it.
For example:
void fillArray(int arr[], int n) { for (int i = 0; i < n; ++i) arr[i] = i*i; } int main() { int myarr[5]; fillArray(myarr, 5); // ok }
Inside the function:
sizeof(arr) — this will return the size of the pointer, not the array.To work correctly and safely with arrays, you can do the following:
const int *arr.Question: Is it possible to find out the size of the original passed array inside the function using the argument
int arr[]viasizeof(arr)?
Answer: No, it is not! sizeof(arr) inside the function will return the size of the pointer type (for instance, 4 or 8 bytes), not the size of the array.
Example:
void f(int arr[]) { printf("%zu ", sizeof(arr)); // size of pointer, not array! } int main() { int x[10]; f(x); // Usually outputs 8 (x86_64) or 4 (x86) }
Story
In an industrial project, the array copying functions attempted to calculate the length of the array on the fly using
sizeof(arr)/sizeof(int)inside the function. In practice, this led to copying only part of the array since the size always equaled 1 (8/8), and the data got overwritten unpredictably.
Story
In a network application, a data sending function accepted a buffer as an array without explicitly specifying its size, causing the entire buffer not to be sent on time, or reading garbage out of the array's bounds, which caused transmission errors and connection instability.
Story
When writing a library for image processing, the programmer did not provide the function for coloring an array of images with a required size parameter. This led to a buffer overflow and crashed the program on certain inputs, which was only discovered during integration testing on a large image.