【问题标题】:strange return behavior in strcat()strcat() 中的奇怪返回行为
【发布时间】: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

标签: c++ string strcat


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢。但是如果我不想制作像 50 这样的硬编码值怎么办?
  • @EagleEye:如果您不想要硬编码的值,则不能将其存储在本地数组中(除非您想使用特定于平台的扩展,例如 VLAs)。您必须改为使用动态内存分配,例如 std::mallocstd:realloc 用于 C 样式的内存分配或 new 用于 C++ 样式的内存分配。您还可以使用某种 C++ 容器,例如 std::string
【解决方案2】:

如果您从 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;
}

【讨论】:

  • 正如我在上面评论的那样,如果我不想硬编码“100”并让它尽可能多地保持打开状态怎么办。有办法吗?
  • @EagleEye • C++ 方式是使用std::string
猜你喜欢
  • 1970-01-01
  • 2019-01-24
  • 2013-12-11
  • 2012-12-01
  • 1970-01-01
  • 2013-07-04
  • 2011-10-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多