Why scanf must take the address of operator
As the title says, I always won开发者_开发问答der why scanf
must take the address of
operator (&).
Because C only has "pass-by-value" parameters, so to pass a 'variable' to put a value into, you have to pass its address (or a pointer to the variable).
scanf does not take "the address of operator (&)". It takes a pointer. Most often the pointer to the output variable is gotten by using the address-of operator in the scanf call, e.g.
int i;
scanf("%i", &i);
printf("number is: %d\n", i);
But that is not the only way to do it. The following is just as valid:
int *iPtr = malloc(sizeof(int));
scanf("%i", iPtr);
printf("number is: %d\n", *iPtr);
Likewise we can do the same thing with the following code:
int i;
int *iPtr = &i;
scanf("%i", iPtr);
printf("number is: %d\n", i);
Because it needs the address to place the value it reads. If you declare you variable as a pointer, the scanf
will not need the &
.
Everyone else has described well that sscanf needs to put its output somewhere, but why not return it? Becuase it has to return many things - it can fill in more than one variable (driven by the formatting) and it returns an int indicating how many of those variables it filled in.
When you input something with standard input device (usually keyboard), the data that comes through must be stored
somewhere. You must point
somewhere in the memory so that data can be stored there. To point
a memory location, you need the address
of that location. So you must pass your variable's address by using &
operator with scanf()
.
as the value is going to be stored,(where?), in the memory address. so scanf() deals with (&) operator.
It tells where to write the input value, as the address of (&) operator give the address of the variable. so, scanf with variable name and address operator meane to write the value at this location. You can also check the address of any variable with the address of(&) operator and %p format specifier in the hexadecimal format.
It's because you are storing something. Just think about how a function must work. With printf, you can think of that as a void function that just outputs the result and then it is done. With scanf you are wanting to RETAIN some data, so you need a pointer aka address where the data you input will be stored even after you leave the function. If you took an argument of data type, say, "int", the data would be lost as soon as you exit the scanf function, in other words, in the next line of code in the parent function, that data you scanfed would be gone.
精彩评论