include<stdio.h>
int main()
{
//char b[10];
char *a="goodone";
//a=b;
scanf("%s",a);//this scanf fails and thow segmentation fault.
printf("%s",a);
}
为什么这不起作用?我用这个scanf尝试了很多,但是当我为变量a *保留内存(通过赋值a = b(注释))时,它工作正常。否则它不会。 我相信char * a将为它的字符串(“goodone”)分配一些内存并将该内存位置返回给它的值。和printf工作很好,这个信念为什么scanf不是? 请从这里节省我......为什么scanf在写入字符串文字时无法按预期工作?
我强烈建议阅读这个问题的[C FAQ条目](http://c-faq.com/aryptr/aryptr2.html)。 – Lundin 2012-02-15 10:56:10
这绝对是一个很好的阅读:[char a \ [\] =“string”之间的区别是什么?和char * p =“string”;](http://stackoverflow.com/questions/9460260/what-is-the-difference-between-char-a-string-and-char-p-string) – 2012-05-29 09:32:38