【问题标题】:format ‘%c’ expects argument of type ‘char*’, but argument 2 has type ‘char**’格式“%c”需要“char*”类型的参数,但参数 2 的类型为“char**”
【发布时间】:2022-01-21 20:55:54
【问题描述】:

我有以下代码尝试使用指针来存储用户请求的值:

#include <stdio.h>
#include <cstring>

char *p_texto = "Prueba Raul";
char *p_texto2;

int main(){
    
    printf("Escriba un texto\n");
    scanf("%c", &p_texto2);
    while(*p_texto2!='\0'){
       printf("%c", *p_texto2);
       p_texto2++;
    }

    return 0;
}

我收到此错误:

format ‘%c’ expects argument of type ‘char*’, but argument 2 has type ‘char**’

我该如何解决这个问题并避免使用char p_texto2[200]

【问题讨论】:

  • 那是C,不是C++
  • 你知道%c 格式在scanf 中的作用吗(在printf 中也是如此)?
  • %c 告诉 scanf() ASSUME 对应的参数是 char * 类型的,这会导致代码中出现未定义的行为(您的编译器可能会为您诊断,但实际上并不是必须的)因为它通过了别的东西。 p_texto2char * 类型,所以 &amp;p_texto2char ** 类型。解决此问题的一种方法是将p_texto2 的类型从char * 更改为char(即删除*)。不过,这将触发循环中的其他错误(即修复第一个问题将暴露代码中您尚未询问的其他问题)。
  • 如果我定义char p_texto2然后在scanfprintf中使用%c,变量是指针?

标签: c++ pointers


【解决方案1】:

您已声明 char 指针 char *p_texto2; 所以,您需要将 p_text02 传递给 scanf("%c", p_texto2); 因为 p_texto2 将保存字符串的基地址,而不是传递指针的地址(&amp;p_texto2)是保存字符串基地址的指针的地址。另外,格式说明符错误需要使用%s在C中获取字符串。

如果您不想使用 char p_texto2[200]; ,建议仅使用 char 指针来保存字符串基址,因为不分配字符串大小,运行时行为是不确定的(可能会发生数据丢失)。 malloc 可用于分配运行时内存。

例如:

int n;
printf("Enter the sizeof string...");
scanf("%d, &n"); // note: the character that can be entered is n-1 as '\0' take the last byte.
p_texto2 = malloc(sizeof(char) * n);
scanf("%[^\n]s", p_texto2);
// Other method to scan a string with spaces.
gets(p_texto2); // this is supported till c11.
fgets(p_texto2, n, stdin);

【讨论】:

  • 您的修复将停止编译器的特定诊断。它也会导致未定义的行为,因为p_texto2 是一个空指针。通过引入未定义的行为(在运行时出现任何症状,编译器不需要诊断)来修复编译错误通常是不好的建议。
  • 感谢@Peter 指出.. 我已经改进了我的答案。
  • @Fizn-Ahmd 我对其进行了测试,但打印无法正常工作。我提出了另一个问题,因为它只打印到第一个空格。
  • @mrc 我已更新 scanf() 以读取带空格的字符串。她的就是它的定义。 ^\n 告诉输入直到没有遇到换行符。在这里,我们使用了 ^ (XOR -Operator ),它给出了 true 直到两个字符不同。一旦字符等于换行符('\n'),^(XOR 运算符)给出 false 以读取字符串。
  • 你可以使用gets(p_texto2);但是,它已从 c11 中删除。所以它可能会在实施时给你一个警告。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-14
  • 2018-11-03
  • 2013-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多