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/