我们都知道数组名指向数组第一个元素的地址,但是为什么我们不能在C语言中将char数组声明为“char* a”格式?为什么当我声明为这种格式时我不能使用scanf("%s",a)?
谢谢大家的回答。
答案是“是的,如果你做得正确的话,你可以。”这就是下面的代码所揭示的内容。重要的是我们为
char
指针分配内存,并且在使用指针之前确认分配成功。
另请注意,我们将字符输入(99 个字符)限制为
scanf()
,因为我们只有 malloc()
100 个字节(99 个字符加上终止 NUL
)。
可运行的代码在这里。
#include <stdio.h> /* printf() */
#include <stdlib.h> /* malloc() */
int main()
{
char *a = malloc(100);
if(a)
{
scanf("%99s",a);
printf("%s\n",a);
}
else
printf("memory allocation failed!\n");
return 0;
}