C语言 当我尝试使用char * it打印字符串时,我在指针中得到分段错误,为什么?



我正在尝试使用char *p,*s;:

scanf("%s", p);
scanf("%s", s);
printf("%sn", p);

它工作到目前为止,但当我在s上调用printf时,它会给我一个分割错误。我不知道为什么。有人能解释一下吗?我使用的是linux和gcc。

在这种情况下,p和s是未初始化的指针;它们没有指向任何有效的记忆。您必须为它们分配指向的内存。请看下面的例子。

char* p = malloc(10); // allocate 10 bytes and point p to them
char* s = malloc(10); // allocate 10 bytes and point s to them
scanf("%s", p);
scanf("%s", s);
printf("%sn", p);
// free the memory when you don't need it anymore
free(p);
free(s);

如果您希望放入p和s中的数据大于10字节,则分配更多。

最新更新