首页 > 解决方案 > strange return behavior in 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;
}

even if i replace the function mystrcat to follows, behaviour is same.

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

strange for me, when i call mystrcat i dont assign to a char* still no compiler's complain. what am i missing here? follow up can u optimize my code with void return type if anyway

标签: c++stringstrcat

解决方案


该字符串start_of被声明为仅足以容纳初始化它的字符串。因此,尝试附加到它会超出数组的末尾。这会调用未定义的行为

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

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

推荐阅读