When you pass an argument to a function you are actually passing a copy of the value. So when you do
void set_int(int x) {
x = 22;
}
int main(int argc, char** argv) {
int a = 20;
set_int(22);
printf("%d\n", a);
}
What you are essentially doing is copying the value of a and putting it into x, now you have to variables, a and x. x is set to 22 and you return out of the function, which C will remove x from memory automatically.
To get the correct variable you can use pointers which are an integer (technically unsigned long but int for our purposes) value that represent a point in memory where another value is stored.
int main(int arc, char** argv) {
int a = 20;
int* b = &a;
}
In this example b is of type "int pointer" which points to a. We can update the set_int()
function to "dereference" our new pointer value.
void set_int(int* x) {
// Dereference out int* with the * operator
// y is out original integer a at the same spot in memory
int y = *x;
// Because we are using a we can now set it to out value of 22
y = 22;
}
int main(int arc, char** argv) {
int a = 20;
int* b = &a;
set_int(b);
// This should print 22
printf("%d\n", a);
return 0;
}
Note that set_int()
is written this way to help understand how pointers work, normally you would compact this into one line:
void set_int(int* x) {
*x = 22;
}
And of course we can also compact our call:
int main(int argc, char** argv) {
int a = 20;
set_int(&a);
printf("%d\n", a);
return 0;
}