Change Array Elements Through a Parameter
Update the same trays
When main passes trays, the function receives an address that leads to the same array elements. It does not receive a second array. Because this parameter is not const, assignments to trays[i] change the caller's elements. The separate count limits the loop; for a read-only function, use const int[] instead.
#include <stdio.h>
void add_one(int trays[], size_t count) {
for (size_t i = 0; i < count; i++) {
trays[i]++;
}
}
int main(void) {
int trays[] = {3, 4};
add_one(trays, 2);
printf("Trays: %d, %d\n", trays[0], trays[1]);
return 0;
}
Before Run, predict 4 and 5. The function does not need to return the array: trays[i] accesses caller-owned elements. This differs from passing one plain int, which only copies that integer value. The pointer parameter itself is still copied. Reassigning that parameter would not replace the caller array. When the helper returns, its pointer and count parameters end their lifetimes, but main still owns the changed elements. With initial values 8 and 10, the same loop would produce 9 and 11.