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 *仍然没有编译器的抱怨。我在这里想念什么?后续您是否可以使用无效的返回类型优化我的代码

iCMS 回答:strcat()中奇怪的返回行为

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

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

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

如果要从C中的函数返回,则不必总是将返回值分配给某个变量。其他printf scanf之类的函数也返回值,但它们不需要给出任何值如果未在调用时将它们分配给某个变量,则会发生错误。

此外,请注意,您的mystrcat函数正在未定义的行为上运行。您将传递两个char数组,并在第一个char数组本身没有任何更多空间分配给它时追加。因此,您应该更改它。

您应该声明要传递给函数的第一个参数的char数组足够长,以便能够在串联后保存数据。您可以按以下步骤更改程序-

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[100] = "going to add ";


    mystrcat(start_of,addthis);

    cout << "after strcat(): " << start_of<< endl;
}
本文链接:https://www.f2er.com/1884167.html

大家都在问