这是一个从 K&R 书中将 string1 复制到 string2 的程序。
#include <stdio.h>
void strcpy_m(char *t1, char *t2);
int main()
{
char *s1 = "this is 1st";
char *s2 = "this is second";
strcpy_m(s1, s2);
printf("%s\t%s\n",s1, s2);
return 0;
}
void strcpy_m(char *t1, char *t2)
{
while((*t2 = *t1) != '\0'){
t2++;
t1++;
}
}
在执行这个程序时,我遇到了段错误。原因是什么?
最佳答案
在您的代码中,s1
和 s2
是指向 string literals 的指针。 。因此,这些指针所指向的内存位置的内容是不可修改的。任何更改内容的尝试都会调用 undefined behavior .
如果您想要一个可修改的字符串,请使用数组,例如
#define ARRSIZ 128 //just some arbitary number
和
char s1[ARRSIZ] = "this is 1st";
char s2[ARRSIZ] = "this is second";
关于c - 此 C 程序中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37001990/