【发布时间】:2020-07-22 18:19:38
【问题描述】:
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 返回类型优化我的代码
【问题讨论】:
-
第一个字符串中没有空间可以连接。这不是 C。
-
您附加到
start_of[],它没有为额外数据分配空间。未定义的行为。 -
如果我不想硬编码任何特定值并保持它打开以占用尽可能多的空间怎么办。有办法吗?
-
是的,使用
std::string。