passbyreference.c Stack diagram
STACK
|==============================|
arg_modifier: | |
| --------- |
| y | *-- |---------------------
| --------- | |
| ------- | |
| x | 10 | | |
| ------- | |
|==============================| |
main: | | |
| | |
| ----------------------------
| | |
| \/ |
| ------ |
| b | 5 | |
| ------ |
| ----- |
| a | 2 | |
| ----- |
|==============================|
- a and b are located in main's stack frame
- in arg_modifier's stack from
- y gets the address of the second argument, x gets the value of the first
- the value of the first argument cannot be modified by the function. the value of the second argument can.
Here is a swap function: try it out if you do not understand how it works:
// do you understand why swap is a void function?
void swap(int *v1, int *v2) {
int temp;
temp = *v1;
*v1 = *v2;
*v2 = temp;
}
int main() {
int x, y;
x = 10;
y = 50;
printf("x = %d y = %d\n", x, y); // prints x = 10 y = 50
swap(&x, &y);
printf("x = %d y = %d\n", x, y); // prints x = 50 y = 10
return 0;
}