Pass an Address to a Function
Fix a stock count through its address
An inventory correction needs to change the count held in main. Passing an int alone would give the function a copy. Passing &stock copies its address instead, and *item then refers to the original stock. The pointer parameter is a copy, but the integer it points to is shared for the duration of the call.
#include <stdio.h>
void correct_count(int *item) {
*item += 4;
}
int main(void) {
int stock = 7;
correct_count(&stock);
printf("Stock: %d\n", stock);
return 0;
}
Follow the call in order:
maincreatesstockwith value 7. Evaluating&stockproduces its address.correct_countstarts a new invocation. Its local pointer parameteritemreceives a copy of that address, not a copy of the integer object.*item += 4follows the copied address and changesstockto 11.mainis waiting, but itsstockremains alive.- The closing brace returns control to
main. The parameteritemstops living.stockstill lives inmain, so the next statement prints 11.
C still passes by value here. Saying “the object was passed by reference” hides the important copy: the argument is an address value. Assigning a different address to item would change only that local parameter. Assigning to *item changes the pointed-to integer instead. This helper requires a pointer to a live, writable int; it is not safe to call it with NULL, the null-pointer value used when no object is selected. A later lesson shows how to check that case.
A pointer parameter ending its lifetime does not end the pointee's lifetime. The reverse matters too: keeping an address does not keep an object alive. We will return to that distinction after the array-pointer exercise. Next, use two addresses to exchange counts.