[英]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:我正在尝试运行一个简单的 C 程序,但出现此错误:
warning: format '%s' expects type 'char *', but argument 2 has type 'char (*)[20]'
警告:格式“%s”需要类型“char *”,但参数 2 的类型为“char (*)[20]”
Running Mac OSX Mountain Lion, compiling in terminal using gcc 4.2.1运行 Mac OSX Mountain Lion,使用 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);
}
scanf("%s",&me);
should be应该
scanf("%s",me);
Explaination:说明:
"%s"
means that scanf
is expecting a pointer to the first element of a char array. "%s"
意味着scanf
需要一个指向 char 数组第一个元素的指针。 me
is an object array and could evaluated as pointer. me
是一个对象数组,可以评估为指针。 So that's why you can use me
directly without adding &
.所以这就是为什么你可以直接使用
me
而无需添加&
。 Adding &
to me
will be evaluated to 'char (*)[20]'
and your scanf is waiting char *
向
me
添加&
将被评估为'char (*)[20]'
并且您的 scanf 正在等待char *
Code critic:代码评论家:
Using "%s"
could cause a buffer overflow if the user input string with length > 20. So change it to "%19s"
:如果用户输入的字符串长度大于 20,则使用
"%s"
可能会导致缓冲区溢出。因此将其更改为"%19s"
:
scanf("%19s",me);
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.除非它是
sizeof
、 _Alignof
或一元&
运算符的操作数,或者是用于在声明中初始化数组的字符串文字,否则类型为“ T
N 元素数组”的表达式将被转换(“衰减") 到一个“指向T
指针”类型的表达式,它将计算数组中第一个元素的地址。
The array me
is declared as a 20-element array of char
;数组
me
被声明为一个 20 元素的char
数组; normally, when the expression me
appears in your code, it will be treated as an expression of type "pointer to char
".通常,当表达式
me
出现在您的代码中时,它将被视为“指向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.表达式
me
将被转换为正确类型的表达式。
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.代替指针
char
,你传递一个指针数组char
( char (*)[20]
这是不什么scanf
为预计%s
转换指定,因此诊断。
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).您实际上必须给出数组的起点(在大多数语言中为 0)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.