这是我编写的一些代码,用来练习使用malloc().特别是,我希望有一个由用户给定的维度和元素组成的字符数组,并打印这些元素.
#include <stdio.h>
#include <stdlib.h>
int main() {
char *ptr;
int d;
printf("Inserire la dimensione dell'array CHAR:\n");
scanf("%d", &d);
ptr = (char *) malloc(d * sizeof(char));
for (int i = 0; i < d; i++) {
printf("Inserire un char:\n");
scanf("%c", ptr[i]);
}
for (int j = 0; j < d; j++) {
printf("%c", ptr[j]);
}
return 0;
}
编译器在第17:warning: fomat "%c" expects argument of type "char", but argument 2 has type "int"
行给出警告.我在第17行try 了scanf("%c", &ptr[i])
,这对我来说似乎也更自然,但代码运行得很糟糕.