为什么这段代码会崩溃?

为什么这段代码会崩溃? 在字符指针上使用strcat非法?

 #include  #include  int main() { char *s1 = "Hello, "; char *s2 = "world!"; char *s3 = strcat(s1, s2); printf("%s",s3); return 0; } 

请参考数组和指针给出正确的方法。

问题是s1指向一个字符串文字,你试图通过将s2附加到它来修改它。 您不能修改字符串文字。 您需要创建一个字符数组并将两个字符串复制到其中,如下所示:

 char *s1 = "Hello, "; char *s2 = "world!"; char s3[100] = ""; /* note that it must be large enough! */ strcat(s3, s1); strcat(s3, s2); printf("%s", s3); 

“足够大”意味着至少strlen(s1) + strlen(s2) + 1+ 1是占空终止符的原因。

话虽如此,你应该认真考虑使用strncat (或者可以说是更好但非标准的strlcat ,如果它可用的话),它们是经过边界检查的,因此远远优于strcat

在这种情况下,正确的方法是在目标字符串(s1)中分配足够的空间来存储6个额外字符(s2)以及字符串的空终止符。

 char s1[14] = "Hello, "; char *s2 = "world!"; char *s3 = strcat(s1, s2); printf("%s",s3); 

以下是strcat()手册的引用:“strcat()函数将src字符串附加到dest字符串,覆盖dest末尾的空字节(’\ 0’),然后添加一个终止空字节。字符串可能不重叠,而dest字符串必须有足够的空间用于结果。“

这里的问题是s1和s2指向“只读”的静态字符串,因此如果您尝试执行strcat操作,在dest参数中使用这样的字符串,您将收到错误。

在这里创建hello world字符串的最好方法是malloc它,这样它就能包含s1和s2。 另外,不要忘记在printf格式字符串的末尾添加’\ n’,否则您可能会感到惊讶。

如果我是你,我会写下这些代码:

 int main() { char* s1 = "Hello "; char* s2 = "World !"; char *s3 = malloc((strlen(s1) + strlen(s2) + 1) * sizeof(char)); /* +1 is for the null terminating character and sizeof(*s3) is the actual size of a char. */ if (s3) { strcat(s3, s1); strcat(s3, s2); printf("%s\n", s3); free(s3); // always free what you alloc when you don't need it anymore. } return 0; }