【问题标题】:memcpy a substringmemcpy 一个子字符串
【发布时间】:2012-01-06 14:49:55
【问题描述】:

我想试试C memcpy功能。我有这个代码:

char destination[40];
memcpy(destination, "My favorite destination is...", 11);
printf(destination);

我想将前 11 个字母复制到目标数组。当我使用 printf 时,结果是“My favorite2”。为什么?

【问题讨论】:

  • 为什么要使用memcpy 表示字符串?为什么不strncpy
  • @KerrekSB strncpy(destination, "My favorite destination is...", 11); 也不会添加 NUL 字节。
  • @rodrigo:好点。多么愚蠢。也许strncat
  • 在这种简单的情况下,仅初始化数组甚至是更好的策略。然后它会与memcpy完美配合。

标签: c substring memcpy


【解决方案1】:

您在 11 个字符的末尾缺少 NULL 终止符 -> Printf 只是打印该部分内存中的任何内容,直到找到 NULL 终止符。

只需添加destination[11] = 0;

应该可以的:)

【讨论】:

    【解决方案2】:

    这是因为memcpy 不会以空字节终止字符串。你可以先用空值填充整个数组:

    memset(destination, 0, sizeof destination);
    

    【讨论】:

      【解决方案3】:

      C 字符串必须以 null 结尾。最简单的解决方案是先将 0 复制到整个字符串中。

      memset(destination, 0, sizeof(destination));
      

      【讨论】:

      • 没有最简单的就是从一开始就正确初始化数组char destination[40] = { 0 }; 会这样做。
      【解决方案4】:
      printf("%.11s","My favorite destination is...");
      

      【讨论】:

        猜你喜欢
        • 2011-08-22
        • 2011-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-23
        • 2011-06-06
        • 2019-05-11
        相关资源
        最近更新 更多