scanf("%s", &me);
should be
scanf("%s", me);
Explanation:
"%s"
means that scanf
is expecting a pointer to the first element of a char
array.
me
is an array object. Array objects are said to decay as a pointer to their first element when passed to a function or used in most expressions except as an argument to sizeof
and _Alignof
. So passing me
or &me[0]
is equivalent and the preferred way is to simply pass the destination as me
.
Adding &
to me
creates a pointer to arrays of 20 chars, with type char (*)[20]
, which is different from the type scanf
expects for %s
. The compiler reports the type mismatch but the program probably behaves as you expect because both &me[0]
and &me
refer to the same memory location so scanf()
really receives the correct address, albeit with an incorrect type.
Code critic:
Using "%s"
could cause a buffer overflow if the user inputs a word longer than 19 bytes, so tell scanf()
to limit the input to 19 bytes by specifying "%19s"
:
scanf("%19s", me);
Note also that the return value of scanf()
is the number of successful conversions, so 1
if input was processed successfully for %s
, and 0
or EOF
otherwise. It is always best to test for scanf()
failure to read all inputs and only use the destination variables in case of success:
#include <stdio.h>
int main(void) {
char me[20];
printf("What is your name?");
if (scanf("%19s", me) == 1)
printf("Darn glad to meet you, %s!\n", me);
else
printf("Sorry you had to leave!\n");
return 0;
}