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?
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?
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).
An array name by itself references the beginning of that array in memory. In this case:
name == &name[0]
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
".