Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ampersand in front of char's array affect scanf? Is it legit?

Tags:

People also ask

What does the ampersand do in scanf?

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.

Why dont we use & in scanf for strings?

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.

Can you have an array of characters?

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.

Is address operator used in scanf () statement to read an array Why?

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?