C passes all of its function parameters by value, not by reference. That means functions cannot modify their parameters directly:
void NoChange(int i) {
printf("Before: %d\n", i);
i = 10; // Changes only the local copy of the variable.
printf("After: %d\n", i);
}
main() {
int n = 1;
printf("Start: %d\n", n);
NoChange(n);
printf("End: %d\n", n);
}
Output:
Start: 1
Before: 1
After: 10
End: 1
If you want a function to change the contents of a variable, you need to pass its address. Then the function can modify the data at that address, which effectively modifies the variable:
void Change(int *i) {
printf("Before: %d\n", *i);
*i = 10; // Changes the memory that i points to.
printf("After: %d\n", *i);
}
main() {
int n = 1;
printf("Start: %d\n", n);
Change(n);
printf("End: %d\n", n);
}
Output:
Start: 1
Before: 1
After: 10
End: 10
So in order for the scanf()
function to store data in a variable, you need to pass it the address of that variable, like this:
int e;
scanf("%d", &e);