-1
int age;
char name[10];

scanf("%d", &age);
scanf("%s", name);

In first scanf function we use '&' symbol before age, but in second scanf we don't use '&' as it is a char array. Can anybody tell me why is so?

itsme
  • 193
  • 4
  • 14
  • 1
    @AVD: Please don't mod-flag a recent question you already VTC'd. Community votes are perfectly fine for this. – ThiefMaster Oct 04 '12 at 07:51

3 Answers3

5

Because the array is already passed as an address, whereas the integer variable is not (and thus explicitly needs its address passed via the & address-of operator).

Amber
  • 507,862
  • 82
  • 626
  • 550
4

An array name by itself references the beginning of that array in memory. In this case:

name == &name[0]
Nocturno
  • 9,579
  • 5
  • 31
  • 39
2

Under most circumstances, an expression of type "N-element array of T" will be converted to ("decay") to type "pointer to T", and the value of the expression will be the address of the first element in the array.

When you write

scanf("%s", name);

the expression name has type "10-element array of char"; by the rule above, it is converted to type "pointer to char", and its value is the same as &name[0]. So scanf receives a pointer value, not an array value.

The exceptions to this rule are when the array expression is an operand of the sizeof, _Alignof, or unary & operators, or is a string literal being used to initialize another array in a declaration.

Note that the expressions name and &name will give you the same value (the address of the first element of the array is the same as the address of the array), but their types will be different; name will have type char *, while &name will have type char(*)[10], or "pointer to 10-element array of char".

John Bode
  • 119,563
  • 19
  • 122
  • 198