This is probably a very elementary problem, but I cannot find the answer anywhere, and this is the first time I've had the problem after several weeks of programming in C. In essence, if I write some code looking something like this:
int size;
scanf("%d", &size);
printf("size is %d", &size);
If I input, say, size = 2, the program will print back out something along the lines of 133692 or a similar number. Why is this? What have I done wrong here?
Try
printf("size is %d", size);
&
gives you the memory location (address) of a variable.
printf("size is %d", &size);
So, the above will print the memory location(address) of size
, not the value stored in size
.
You have to do:
printf("size is %d", size);
instead. This prints the value of the int
object size
.
But
printf("size is %d", &size);
is undefined behavior.
You are printing the address of size
, i.e., &size
.
Just pass a plain size
.
Remove the &
in the printf
statement as &size
--> prints the address.
printf("size is %d", size);
The calling conventions are different in printf, and scanf.
Printf's arguments are typically by value (no &), but scanf has to have pointers. (&)
(You can't put a new value to e.g. 1.0, but you can print it...)