格式"%c"需要"char*"类型的参数,但参数2的类型为"char*



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

#include <stdio.h>
#include <cstring>
char *p_texto = "Prueba Raul";
char *p_texto2;
int main(){

printf("Escriba un texton");
scanf("%c", &p_texto2);
while(*p_texto2!=''){
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]

您已经声明了char指针char *p_texto2;,因此需要将p_text02传递给scanf("%c", p_texto2);,因为p_texto2将保存字符串的基地址,而您传递的是指针的地址(&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 '' 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);

最新更新