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?
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.
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.
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.
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.).
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.
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).
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