c - 如何使用 strcat() 函数?

标签 c string pointers c-strings strcat

我是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. If dest 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/

相关文章:

c# - 为什么这会出现在我的 C# 字符串 : £ 中

python - 将字符串中的日期与今天的日期进行比较

C链表不能在开头添加元素

c - 无法设置 Pthread 优先级

c++ - 对已转换为字符串的整数 vector 进行排序

objective-c - 苹果机,OpenGL 4 : drawing on FrameBuffer does not work

c++ - 如何在 C++ 中用数组和指针实现插入排序算法?

c - 字符串操作在 print 语句进入时返回正确的值,在删除时中断

c - 为什么 string.h 函数会出现段错误?

c++ - 初始化 pthread 互斥锁