![](/img/trans.png)
[英]format '%s' expects argument of type 'char *', but argument 2 has type 'char **'
[英]format ‘%c’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[0]’
我想创建一个程序,您可以在其中提供输入并根据输入提供输出,但是我在输入部分遇到了一些麻烦。 我首先创建了一个未初始化的字符串,并希望将输入存储在其中。 但是当我编译时,它显示了这个错误:
格式 '%c' 需要类型为 'char *' 的参数,但参数 2 的类型为 'char (*)[0]'
我在网上查看过,但无法获得有关如何解决此问题的答案。
到目前为止我的代码(在 C 中):
#include <stdio.h>
#include <stdlib.h>
int main() {
char string[] = "";
scanf("%c", &string);
}
&string
是一个指向数组的指针,只传递string
就足够了。 string
长度为 1 并且适合单个字符,但不要尝试将其解释为字符串,因为它不会以空字符结尾。
#include <stdio.h>
#include <stdlib.h>
int main() {
char string[] = "";
scanf("%c", string);
}
或者,您可以这样做。 它是等效的,有人说它更具可读性。
int main() {
char string[] = "";
scanf("%c", &string[0]);
}
您的问题陈述是“我想创建一个程序,您可以在其中提供输入,并根据输入提供输出”
你可以尝试这样的事情:
#include <stdio.h>
#include <stdlib.h>
#define MAX_LEN 50
int main(){
char string[MAX_LEN+1];
//fgets is safe & would read whitespaces
fgets(string, MAX_LEN, stdin);
printf("%s", string);
return 0;
}
关于;
scanf("%c", &string);
变量string
是一个数组。 在 C 中,对数组的“裸”引用降级为数组第一个字节的地址。 因此,对scanf()
参数&string
的调用是要求地址的地址。
通常编译器会输出警告(如您所见)但会生成正确的代码。 为避免此问题,当参数是对数组的“裸”引用时,请从参数中删除&
。 IE
scanf("%c", string);
更好的是,使用:
scanf("%c", &string[0]);
对于健壮的代码,请始终检查任何scanf()
系列函数的返回值。 通常,它们返回成功输入格式转换说明符的数量。 所以一个更好的例子是;
if( scanf("%c", &string[0]) != 1 )
{
fprintf( stderr, "scanf for first char of array -string- failed" );
}
这种错误(通常)是不可恢复的,所以通常代码是:
if( scanf("%c", &string[0]) != 1 )
{
fprintf( stderr, "scanf for first char of array -string- failed" );
exit( EXIT_FAILURE );
}
其中exit()
和 EXIT_FAILURE 都在头文件中公开: stdlib.h
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.