Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is & used before a variable?

Tags:

c

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;
}
like image 783
Sahriar rahman supto Avatar asked Nov 02 '13 21:11

Sahriar rahman supto


Video Answer


2 Answers

& 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;
}
like image 134
Paul Roub Avatar answered Oct 31 '22 00:10

Paul Roub


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.

like image 33
Zach Stark Avatar answered Oct 31 '22 00:10

Zach Stark