Why is &
used here before decks
(scanf("%i", &decks)
)?
And if my input is any letter like 'k' then it shows an output like "1929597720". Why?
#include <stdio.h>
int main(){
int decks;
puts("enter a number of decks:");
scanf("%i", &decks);
if (decks<1) {puts("Please enter a valid deck number");
return 1;
}
printf("there are %i cards\n", (decks*52));
return 0;
}
&
before a variable name means "use the address of this variable". Basically, you're passing a pointer to decks
to scanf()
As for what happens when you enter "k" (or other invalid input) - scanf()
is failing, and you're seeing whatever random data was already in decks
(which was never initialized).
To avoid this, check the return value of scanf()
, and initialize decks
.
int decks = 0, scanned;
puts("enter a number of decks:");
int scanned = scanf("%i", &decks);
if ((scanned < 1) || (decks < 1)) {
puts("Please enter a valid deck number");
return 1;
}
When passing stuff to scanf(), you need to pass in a pointer to the variable, not the variable itself. The & means "Don't take the variable, take the place in memory where this variable is stored." It's a little complicated, but it's necessary so that C can change the value of the variable.
Also, change your format string to
scanf("%d", &decks);
The garbage is because you don't initialize decks. If you put in int decks = 0
, you would always get 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With