6

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;
}

3 Answers 3

5

& 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;
}
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Well no, %i is fine; it can be used to read in stuff like 0xabcd
1

As every good C tutorial will teach you, the & sign is for getting a variable's address.

In the case of scanf(), this is necessary in order to tell scanf() where to put the requested data.


If you input a letter like k, or any non-number, scanf() will be disturbed by that, and if you would check scanf()'s return value, it would tell you that 0 items are read instead of 1.

In that case, the content of the given variable is unchanged and contains random garbage. And this is as well what you output.

5 Comments

I am reading head to c ebook. can you refer me some good book more for basic things.. I am very cofused about "getting an address's variable"
I think he actually meant "getting a variable's address"
As every good book will teach you as well, the & sign is for getting a variable's address. Never saw that in Hunt for Red October. (couldn't resist)
@Sahriarrahmansupto Ouch. Of course. Thanks to all for pointing it out and editing.
@ryyker You are right. BTW, the local telephone book doesn't contain this as well. I'll have to change that claim...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.