【发布时间】:2021-01-14 01:17:32
【问题描述】:
我不明白为什么当我使用 char * ss 和 char * ss2 运行 strcpy (ss, ss2) 时,它会显示分段错误。 strcpy() 只是要求 2 个 char * 类型的 args,所以我不明白这个问题
#include <stdio.h>
#include <string.h>
int main()
{
char *s;
char *s2 = "hello";
s = s2;
printf ("s=%s\ns2=%s\n", s,s2);
char *ss;
char *ss2 = "hello";
strcpy (ss, ss2);//why segmentation fault?
printf("ss=%s\nss2=%s\n",ss,ss2);
}
return 0;
【问题讨论】:
-
char *ss;这是一个未初始化的指针,写入它是未定义的行为。 -
如果你总是问自己“我的指针指向什么有效内存”(例如,我的指针作为它的值保存的地址是什么),你将消除 99% 的指针问题。一些提供指针基本讨论的链接可能会有所帮助。 Difference between char pp and (char) p? 和 Pointer to pointer of structs indexing out of bounds(?)...(忽略标题,答案讨论指针基础知识)