为什么这段代码会崩溃?strcat在字符指针上使用非法?
#include <stdio.h>
#include <string.h>
int main()
{
char *s1 = "Hello, ";
char *s2 = "world!";
char *s3 = strcat(s1, s2);
printf("%s",s3);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
请在引用数组和指针时给出正确的方法.
Jam*_*lis 11
问题是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);
Run Code Online (Sandbox Code Playgroud)
"足够大"意味着至少strlen(s1) + strlen(s2) + 1.这+ 1是为了解释null终止符.
话虽如此,你应该认真考虑使用strncat(或者可以说是更好但非标准的strlcat,如果有的话),它们受到边界检查,因此远远优于strcat.
| 归档时间: |
|
| 查看次数: |
4316 次 |
| 最近记录: |