c++ - 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
解决方案
该字符串start_of
被声明为仅足以容纳初始化它的字符串。因此,尝试附加到它会超出数组的末尾。这会调用未定义的行为。
您需要使数组足够大以容纳连接的字符串。
char start_of[50] = "going to add ";
推荐阅读
- json - Golang json根据键值对解组
- asp.net - 在 Telerik 网格中显示总计
- javascript - 如何将 [object Map] 转换为车把中的可显示文本
- autodesk-forge - 翻译后删除源文件
- javascript - 如何在摩纳哥编辑器中监控文件是否从外部更改?
- elasticsearch - Elasticsearch Java API 将直接生成器添加到短语建议器
- reactjs - React Material UI 删除选定的单元格
- selenium-chromedriver - selenium chrome 驱动程序,在 URL 中收到“数据:”,并且无法打开正确的网页
- php - 刷新令牌到期日期
- angular - 从类型 T 更改为类型 Observable
在角