I have the following multiple-choice question and I cannot figure out why (A) and (C) are incorrect, any explanation would be appreciated! The only correct answer in the following question is (B).
Which of the following is a correct usage of scanf?
(A) int i=0; scanf("%d", i);
(B) int i=0; int *p=&i; scanf("%d", p);
(C) char *s="1234567"; scanf("%3s", &s);
(D) char c; scanf("%c", c);
scanf
wants a correct address where to store the result:i
is passed here by value, no address: wrong.p
is a pointer to int,scanf
can store its result here: right&s
is the address of a pointer tochar *
, you cannot store a string there: wrongc
is passed by value, not an address: wrongscanf
with a specifier as%d
takes an input as the address of the location to be scanned.With 1. you are giving the input as
i
which is wrongWith 2. you are giving the input as
p
which has the address ofi
.This is set during the initialization asint *p=&i
. So this is correct.With 3. the specifier is
%s
. This takes an input of the address at which to start storing the string. The input ofs
is an array and already contains the address.&s
is wrong.With 4. You are using specifier of
%c
which also takes the address of the location. So giving an input ofc
is wrong in this case, as to get the address of the location you need&c
Learn this:
Expanation: what is the address of i variable? for that & operator gives the address of i variable. scanf() getting user input and store the values on that address.
Explanation: In this case, you were assigning string to character pointer and that is located in code section. Main aim of this option is the we can not modify the code section. But in this case we are modifying pointer. so after that pointer point to the newly assigned address else it may entered wrong address then get segmentation fault. so we lost previously assigned string.
You must pass a pointer to the function so that it knows where in memory to store the value. If you just pass by value, it will treat that as a memory address, and all hell breaks loose. So you use
&
to take a reference (i.e. the memory address) of your variable.That's why A and D are wrong.
As for C, it looks right because you are supplying a pointer, but you are actually referencing that pointer. So
scanf
will write over the pointer itself, not the memory it points to.If you had just supplied
s
, then we get into another no-no land. The pointer is to a string literal which you are not allowed to modify. However, if it was not a literal but an array using the literal as an initializer it would be okay, provided you didn't read in more data than it can store:For A:
This should be:
Take a look at the signature of
scanf()