4

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

In C when we use the scanf() function to get user input, we always use the & sign before the variable. For example:

  scanf("%d", &number);
  scanf("%c", &letter);

This ensures our input is stored in proper address. But in case of a string we do not use &.

Why is that?

Community
  • 1
  • 1
tarashish
  • 1,865
  • 20
  • 30

2 Answers2

13

A "string" in C is the address of a character buffer.
You want scanf to fill the memory in the buffer, which is pointed to by the variable.

In contrast, an int is a block of memory, not an address. In order for scanf to fill that memory, you need to pass its address.

SLaks
  • 800,742
  • 167
  • 1,811
  • 1,896
1

Since the identifier buf in char buf[512]; degrades to a pointer to the first element of the array you don't need to specify a pointer to the buffer in the argument to scanf. By passing &buf the pointer passed to scanf is now a doubly-indirect pointer (it is a pointer to a pointer to the beginning of the buffer) and will likely cause the program to crash or other bad behaviour.

jmkeyes
  • 3,653
  • 15
  • 18