'warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘char (*)’

I am trying to run a simple C program but I am getting this error:

warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘char (*)[20]’

Running Mac OSX Mountain Lion, compiling in terminal using gcc 4.2.1

#include <stdio.h>

int main() {
    char me[20];

    printf("What is your name?");
    scanf("%s", &me);
    printf("Darn glad to meet you, %s!\n", me);

    return (0);
}


Solution 1:[1]

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 object array and could be evaluated as pointer. That's why you can use me directly without adding &. Adding & to me will be evaluated to 'char (*)[20]' and your scanf is waiting char *

Code critic:

Using "%s" could cause a buffer overflow if the user input string's length is bigger than 20, so change it to "%19s":

scanf("%19s", me);

Solution 2:[2]

Except when it is the operand of the sizeof, _Alignof, or unary & operators, or is a string literal being used to initialize an array in a declaration, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T", and it will evaluate to the address of the first element in the array.

The array me is declared as a 20-element array of char; normally, when the expression me appears in your code, it will be treated as an expression of type "pointer to char". If you had written

scanf("%s", me);

then you wouldn't have gotten the error; the expression me would have been converted to an expression of the correct type.

By using the & operator, however, you've bypassed that rule; instead of a pointer to char, you're passing a pointer to an array of char (char (*)[20]), which is not what scanf expects for the %s conversion specifier, hence the diagnostic.

Solution 3:[3]

Another way you could fix this issue is by doing this:

scanf("%s",&me[0]);

You actually have to give the array's starting point (which in most languages is 0).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 WicCaesar
Solution 2 John Bode
Solution 3 Matthew