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

前端 未结 3 1947
慢半拍i
慢半拍i 2020-12-08 03:28

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]’<

3条回答
  •  醉梦人生
    2020-12-08 03:42

    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.

提交回复
热议问题