警告:格式为“%s",预期类型为"char *",但参数2的类型为"char(*)" [英] warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘char (*)’
问题描述
我正在尝试运行一个简单的C程序,但出现此错误:
I am trying to run a simple C program but I am getting this error:
警告:格式为%s"的类型应为"char *",但参数2的类型为"char(*)[20]"
warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘char (*)[20]’
运行Mac OSX Mountain Lion,使用gcc 4.2.1在终端中进行编译
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);
}
推荐答案
scanf("%s",&me);
应该是
scanf("%s",me);
说明:
%s"
表示 scanf
需要一个指向char数组第一个元素的指针. me
是一个对象数组,可以评估为指针.这就是为什么您可以直接使用 me
而不添加&
的原因.将&
添加到 me
将被评估为'char(*)[20]'
,并且您的scanf正在等待 char *
"%s"
means that scanf
is expecting a pointer to the first element of a char array. me
is an object array and could evaluated as pointer. So 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 *
代码注释者:
如果用户输入的字符串长度> 20,则使用%s"
可能导致缓冲区溢出,因此将其更改为%19s"
:
Using "%s"
could cause a buffer overflow if the user input string with length > 20. So change it to "%19s"
:
scanf("%19s",me);
这篇关于警告:格式为“%s",预期类型为"char *",但参数2的类型为"char(*)"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!