为什么在字符指针上使用 strcat 会崩溃? [英] Why does using strcat on character pointers crash?
问题描述
为什么这段代码会崩溃?在字符指针上使用 strcat
是非法的吗?
why does this code crash?
is using strcat
illegal on character pointers?
#include <stdio.h>
#include <string.h>
int main()
{
char *s1 = "Hello, ";
char *s2 = "world!";
char *s3 = strcat(s1, s2);
printf("%s",s3);
return 0;
}
请给出引用数组和指针的正确方法.
please give a proper way with referring to both array and pointers.
推荐答案
问题是 s1
指向一个字符串文字,而您试图通过附加 s2
给它.不允许修改字符串文字.您需要创建一个字符数组并将两个字符串复制到其中,如下所示:
The problem is that s1
points to a string literal and you are trying to modify it by appending s2
to it. You are not allowed to modify string literals. You need to create a character array and copy both strings into it, like so:
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
是为了说明空终止符.
"Large enough" means at least strlen(s1) + strlen(s2) + 1
. The + 1
is to account for the null terminator.
话虽如此,您应该认真考虑使用经过边界检查的 strncat
(或者可以说更好但非标准的 strlcat
,如果可用),并且因此远远优于 strcat
.
That having been said, you should seriously consider using strncat
(or the arguably better but nonstandard strlcat
, if it is available), which are bounds-checked, and thus are far superior to strcat
.
这篇关于为什么在字符指针上使用 strcat 会崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!