views:

225

answers:

3

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?

A: 

Err, nm, I'm tired :(

Adam
I'd delete this, since it's not an answer. Normally, you would delete the question. That said, your question, even if you figured it out, is still valid, so no need to delete it.
GMan
+4  A: 

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.

GMan
+2  A: 

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

Steve Emmerson