【发布时间】: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_texto2是char *类型,所以&p_texto2是char **类型。解决此问题的一种方法是将p_texto2的类型从char *更改为char(即删除*)。不过,这将触发循环中的其他错误(即修复第一个问题将暴露代码中您尚未询问的其他问题)。 -
如果我定义
char p_texto2然后在scanf和printf中使用%c,变量是指针?