我是C语言的新手。我正在尝试使用 strcat 函数。
#include <stdio.h>
#include <string.h>
int main(int argc, const char *argv[]) {
char s1[] = "12345";
char s2[] = "abcde";
strcat(s1, s2);
puts(s1);
puts(s2);
return 0;
}
这个运行正常,但是
#include <stdio.h>
#include <string.h>
int main(int argc, const char *argv[]) {
char* s1 = "12345";
char* s2 = "abcde";
strcat(s1, s2);
puts(s1);
puts(s2);
return 0;
}
最后一个没有返回结果。为什么两种不同的声明方式在strcat函数中返回的结果不同。提前致谢。
最佳答案
这两个代码片段都调用了未定义的行为。在第一个代码段中,s1
没有足够的空间容纳除六个字符以外的任何其他字符。
在第二个片段中,您试图修改字符串文字。任何修改字符串文字的尝试都会导致未定义的行为。
阅读strcat
man page :
[...] The strings may not overlap, and the
dest
string must have enough space for the result. Ifdest
is not large enough, program behavior is unpredictable; buffer overruns are a favorite avenue for attacking secure programs.
关于c - 如何使用 strcat() 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45375524/