Reputation: 2596
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?
Upvotes: 10
Views: 12154
Reputation: 504303
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 decays into a pointer).
printf
does the same, treating %s
as a pointer-to-string.
Upvotes: 10
Reputation: 7842
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).
Upvotes: 6