c++ - strcat() 中奇怪的返回行为

标签 c++ string strcat

void mystrcat(char* to, const char* from) {
    while (*to) to++;
    while (*from) *to++ = *from++;
    *to = '\0';
}

int main() {
    char addthis[]= "rest of the sentence";
    char start_of[] = "going to add ";


    mystrcat(start_of, addthis);

    cout << "after strcat(): " << start_of<< endl;
}

即使我将函数 mystrcat 替换为以下内容,行为也是相同的。

char* mystrcat(char* to, const char* from) {
    while (*to) to++;
    while (*from) *to++ = *from++;
    *to = '\0';
    return to;
}

对我来说很奇怪,当我调用 mystrcat 时,我没有分配给 char* ,但仍然没有编译器提示。我在这里缺少什么?无论如何,你可以用 void 返回类型优化我的代码吗

最佳答案

字符串start_of被声明为仅足够长以容纳其初始化的字符串。因此,尝试追加到它会超出数组的末尾。这会调用 undefined behavior .

您需要使数组足够大以容纳连接的字符串。

char start_of[50] = "going to add ";

关于c++ - strcat() 中奇怪的返回行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63040767/

相关文章:

将文件扩展名连接到 C 中的基本名称

c++ - 如何检查一组值中的一个是否相等?

java - 无法使用 StringBuilder 将字符连接到字符串

java - 如何减去两个字符串

c++ - 字的字节返回比它应该的少一

c - 函数未接收我作为 const char * 发送的内容

c++ - 在排序数组中找到a [i] = i的最有效方法是什么?

C++ 多回调函数

c++ - 缺少 msvcr100.dll - 如何使可执行文件向后兼容

java - 如何在 Java 中比较字符串?