Passing variables by reference
If we have a variable x and we pass the address of x to a function, then that function can edit the value of x.
Source Code:
(main.c)
#include <stdio.h>
void f(x) /* This function takes an integer */
int x;
{
x=x+5;
}
void g(x) /* This function takes the address of an integer (aka a pointer) */
int *x;
{
(*x)=(*x)+5;
}
int main(){
int x;
x=3;
printf("x=%d\n", x);
f(x);
printf("x=%d\n", x);
g(&x); /* &x is the address of x */
printf("x=%d\n", x);
return 0;
}
Output:
To compile: