When I compile scanf("%s", &var);, gcc sends back a warning:
warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘char (*)[20]’
however when I compile scanf("%s", var);, no warning is applied. Both pieces of code work and the book I am reading specifically says to use the ampersand, but even it doesn’t in some of the examples.
My question is, should I continue to use the ampersand, even when the book doesn’t specify?
From what you’ve posted
varis a char array. In that case, you don’t need the ampersand, just the namevarwill evaluate to a (char *) as needed.Details:
scanf needs a pointer to the variable that will store input. In the case of a string, you need a pointer to an array of characters in memory big enough to store whatever string is read in. When you declare something like
char var[100], you make space for 100chars with var[0] referring to the first char and var[99] referring to the 100th char. The array name by itself evaluates to exactly the same thing as&var[0], which is a pointer to the first character of the sequence, exactly what is needed by scanf. So all you need to do isscanf("%s", var);, but be aware thatscanfdoes not enforce size constraints on input strings, so if the user inputs a 101 length string your will have a buffer overrun, which will result in bugs or, even worse, security problems. The better choice is generallyfgetswhich does allow size constraints for input strings.