10

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?

Adam
  • 2,606
  • 4
  • 19
  • 14

2 Answers2

10

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.

GManNickG
  • 494,350
  • 52
  • 494
  • 543
6

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
  • 7,702
  • 5
  • 33
  • 59
  • 1
    More precisely, an expression of array type is implicitly converted ("decays") to a pointer to the array's first element in most but not all contexts. A function argument happens to be one of the contexts where the conversion happens. – Keith Thompson Jan 19 '12 at 06:17