The “%d” in scanf allows the function to recognise user input as being of an integer data type, which matches the data type of our variable number. The ampersand (&) allows us to pass the address of variable number which is the place in memory where we store the information that scanf read.
In case of a string (character array), the variable itself points to the first element of the array in question. Thus, there is no need to use the '&' operator to pass the address.
A character array is a sequence of characters, just as a numeric array is a sequence of numbers. A typical use is to store a short piece of text as a row of characters in a character vector.
The arguments of the scanf() function are the pointers types, we must provide either an address of a variable or a pointer (which contains the address of the variable). Therefore, if we are using a pointer in scanf(), we don't use address of (&) operator, because pointer contains the address itself.
When we usually input the string, we do this:
#include <stdio.h>
int main()
{
char str[256];
scanf("%s",str);
//Other Operation
}
But, today, in programming class, one of my friends wrote scanf
line like this:
scanf("%s",&str);
and it pass the compilation, and works.
The question is, I'd like to know if this is "legal" in C or not, or just an undefined behavior?
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