0

Why scanf requires a & for int but none for a char?

  int main ()
     {
        char str [80];
        int i;

        printf ("Enter your family name: ");
        scanf ("%s",str);  
        printf ("Enter your age: ");
        scanf ("%d",&i);

        return 0;
    }
user2246674
  • 7,621
  • 25
  • 28
extensa5620
  • 681
  • 2
  • 8
  • 22
  • 2
    Search for "array pointer decay" for why using `str` as a scanf argument works without an `&`. It could also be written as `&str[0]` (which also means "the pointer to the first element", but said more explicitly). Ref. http://stackoverflow.com/questions/1461432 , http://stackoverflow.com/questions/7378555 – user2246674 Aug 10 '13 at 23:24
  • Just remember that the address-of operator (`&`) results in a pointer, so `&some_char_array` returns a `char (*)[80]`, i.e., a pointer to array of 80 char. Not what you wanted. – Ed S. Aug 10 '13 at 23:37
  • 2
    "Why scanf requires a & for int but none for a char?" - it does require `&` for a char too. But you don't have a char, you have a whole **array** of them. –  Aug 10 '13 at 23:38

4 Answers4

1

scanf() requires a pointer (memory address) where it scans data into. Although str is an array of characters, when str is used in an expression (e.g. as an argument to scanf) it actually means the memory address of its first element. For an int, however, you have to explicitly tell scanf() to use its memory address, which is why you use the & (address-of) operator.

1''
  • 26,823
  • 32
  • 143
  • 200
1

becase is str a address of the array's fisrt item while i is only the name of int, &i means the address of int i

Lidong Guo
  • 2,817
  • 2
  • 19
  • 31
1

Standard library function scanf() expects a pointer corresponding to the data you want to read. So you are always required to pass a pointer.

In case of char[], the array name decays into a pointer to the first element of the array, which is why you don't use & for char arrays. In fact, using an ampersand (&) for a char array when passing to scanf(), is wrong as the type of &charArray is char (*)[N] whereas scanf() expects a char* for the format specifier %s.

In case if you have pointers, then you can simply pass them directly. E.g.

int *p;
char *c;
p = malloc(sizeof(int)); // one int
c = malloc(100); // 100 bytes  
scanf("%d%99s", p, c);

As said above, you don't use & here as the arguments are already pointers and using & is wrong as that will make them pointer to pointers.

So you use & whenever the argument to scanf() is not a pointer to an object of the type you want to read in.

P.P
  • 117,907
  • 20
  • 175
  • 238
0

str decays to a pointer because it's an array (therefore it points to its first element, this does not mean that arrays and pointers are the same thing). i requires & because scanf needs the address where to store the value, so it needs the address of i.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
Jesus Ramos
  • 22,940
  • 10
  • 58
  • 88