C passes arguments by value, including pointers. To modify a variable belonging to the calling function, pass its address to a function and use a pointer parameter to access the original object.
#include <stdio.h>
void changeValue(int *ptr)
{
*ptr = 100;
}
int main(void)
{
int value = 10;
printf("Before function call: %d\n", value);
changeValue(&value);
printf("After function call: %d\n", value);
return 0;
}
Example Output #
Before function call: 10
After function call: 100
Explanation #
The function call passes the address of value:
changeValue(&value);
The address is copied into the pointer parameter ptr:
void changeValue(int *ptr)
The dereference expression:
*ptr = 100;
modifies the integer object at the address stored in ptr. Since that address refers to value, the original variable changes to 100.
How the Pointer Works #
| Expression | Meaning |
|---|---|
value |
The integer value stored in the calling function |
&value |
The address of the original variable |
int *ptr |
A pointer parameter that stores the address |
ptr |
The copied pointer value |
*ptr |
Access to the integer object pointed to by ptr |
A function can modify an original variable through a pointer, provided the pointer refers to a valid, writable object. This is commonly used when a function needs to update caller-owned data or return multiple results through output parameters.