Pass an Array and Its Length
Pass the readings with their count
To reuse an array in a helper, pass where its elements start and how many the helper may access:
The desk has three readings to pass to a function. Two rules meet at this call. The array expression in main converts to a pointer to its first element. Separately, the parameter declaration const int readings[] is adjusted to const int *readings. The function receives that pointer value by copy, just as in the previous section.
That pointer does not carry the array's length, and sizeof readings inside the function measures the pointer rather than the whole array. Pass the element count separately. The const qualifier prevents writes through this parameter; it does not make the caller’s original array permanently read-only.
#include <stdio.h>
int first_reading(const int readings[], size_t count) {
if (count == 0) {
return 0;
}
return readings[0];
}
int main(void) {
int readings[] = {18, 20, 22};
size_t count = sizeof readings / sizeof readings[0];
printf("First: %d\n", first_reading(readings, count));
return 0;
}
The two names readings have different roles: an array in main and a pointer parameter in first_reading. Compute sizeof readings / sizeof readings[0] in main, before that array information is lost at the call.
The call supplies two copied values: the address of element 0 and the count 3. The array itself stays in main and remains alive while the helper runs. Passing a count does not make C check it: the caller must supply enough live elements for the promised count. Here count == 0 means the helper returns 0 without reading any element; 0 is a chosen fallback, not a universal rule for empty data.
Run the example and look for 18. The next exercise uses the count to visit every element, rather than just the first.