In C, all function arguments are passed by value; any changes to the formal parameter of the function are not reflected in the actual parameter. For example:
void foo(int bar) { bar = bar + 1; } int main(void) { int x = 0; printf("x before foo = %d\n", x); foo(x); printf("x after foo = %d\n", x); return 0; }
The output of the program will be
x before foo = 0
x after foo = 0
because bar gets the value of x (0), not a reference to x . Changing bar does not affect x .
In C, the way around this is to pass a pointer to a variable:
void foo(int *bar) { *bar = *bar + 1; } int main(void) { int x = 0; printf("x before foo = %d\n", x); foo(&x); printf("x after foo = %d\n", x); return 0; }
Now exit program
x before foo = 0
x after foo = 1
This time, the formal parameter bar not int, but a pointer to int and receives the address x (given by the expression &x in the call to foo ), not the value contained in x. The expression *bar means "get the value in the location bar," so *bar = *bar + 1 corresponds to x = x + 1 .
Since scanf() needs to be written in its arguments, it expects these arguments to be entered as pointers. The conversion specifier "% d" expects the corresponding argument to be a pointer to int ( int * ), the conversion specifier "% u" expects a pointer to unsigned int ( unsigned * ), "% s" expects a pointer to char ( char * ), " % f "expects a pointer to float ( float * ), etc. In your example, since a printed int , you need to use the &a expression to get the pointer.
Note that if a already a pointer type, you would not need to use the & operator in the scanf() call:
int main(void) { int a, *pa;
Note also that when passing an array to a function (for example, when using the% s conversion specifier to read a string) you do not need to use the & ; an array expression will be implicitly converted to a pointer type:
int main(void) { char name[20]; ... scanf("%19s", name);