Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't scanf need an ampersand for strings and also works fine in printf (in C)?

I am learning about strings in C now.

How come to use scanf to get a string you can do

scanf("%s",str1);

and for printf you can do

printf("The string is %s\n", str1);

I understand that for scanf it is because the string is just a character array which is a pointer, but for printf, how is it that you can just put the variable name just like you would for an int or float?

like image 604
Adam Avatar asked Dec 19 '09 03:12

Adam


People also ask

Why does scanf not need & 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.

Why ampersand is used in scanf not in printf?

The reason is, scanf() needs to modify values of a and b and but they are local to scanf(). So in order to reflect changes in the variable a and b of the main function, we need to pass addresses of them. We cannot simply pass them by value.

Why ampersand is used in scanf in C?

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.

Does scanf work for Strings in C?

You can use the scanf() function to read a string. The scanf() function reads the sequence of characters until it encounters whitespace (space, newline, tab, etc.).


2 Answers

scanf needs the address of the variable to read into, and string buffers are already represented as addresses (pointer to a location in memory, or an array that decomposes into a pointer).

printf does the same, treating %s as a pointer-to-string.

like image 155
GManNickG Avatar answered Oct 27 '22 02:10

GManNickG


In C, variables that are arrays become a pointer to the first element of the array when used as function arguments -- so your scanf() sees a pointer to memory (assuming "str1" is an array).

In your printf(), "str1" could be either a pointer to a string or a character array (in which case the argument seen by printf() would be a pointer to the first element of the array).

like image 44
Steve Emmerson Avatar answered Oct 27 '22 03:10

Steve Emmerson