警告:格式“%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屋!