为什么这code会崩溃吗? [英] why does this code crash?
问题描述
为什么这code会崩溃吗?
使用 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
是占空终止符。
虽然这样说,你应该认真考虑使用 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
.
这篇关于为什么这code会崩溃吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!