【问题标题】:Copying array into array into another array (of strings), duplicate its content in C将数组复制到另一个数组(字符串)中,在C中复制其内容
【发布时间】:2020-09-04 21:43:30
【问题描述】:

我开始学习 C 的基础知识,但我被这个产生这种奇怪输出的简单程序卡住了。我要做的是使用 memcpy() 函数将数组的内容复制到另一个数组中。

#include <stdio.h>
#include <string.h>

int main()
{   
    char source[13] = "Hello, World!";
    char destination[13];

    memcpy(&destination, &source, 13);

    printf("%s\n", destination);
    return 0;
}

“奇怪”的输出是:

Hello, World!Hello, World!(

让我想知道为什么会发生这种情况的是,如果我在 memcpy 中将输出从 13 更改为 12,那么输出是正确的,显然没有最后一个字符:

Hello, World

所以,我的问题是:“我缺少什么?有一些我不知道的理论基础吗?”

【问题讨论】:

    标签: c arrays printf c-strings memcpy


    【解决方案1】:

    转换说明符%s 用于输出由零字符'\0' 终止的字符序列。

    但是这个数组

    char source[13] = "Hello, World!";
    

    不包含字符串,因为它只有 13 个元素。所以它没有空间用于作为初始化器的字符串文字的终止零。

    要输出数组,你需要使用另一种格式

    printf("%.*s\n", 13, destination);
    

    这是一个演示程序

    #include <stdio.h>
    #include <string.h>
    
    int main()
    {   
        enum { N = 13 };
        char source[N] = "Hello, World!";
        char destination[N];
    
        memcpy( destination, source, N );
    
        printf( "%.*s\n", N, destination );
    
        return 0;
    }
    

    它的输出是

    Hello, World!
    

    或者,您可以将数组定义为具有 14 个元素,其中一个元素保留用于终止零。

    请注意,在memcpy 的调用中使用以下参数是正确的

    memcpy( destination, source, 13 );
    

    【讨论】:

      【解决方案2】:

      C 中的每个字符串都需要以零结尾。所以你的数组的长度太小了,无法容纳字符串,程序调用了 UB。

      改为:

      #include <stdio.h>
      #include <string.h>
      
      int main()
      {   
          char source[14] = "Hello, World!";
          char destination[14];
      
          memcpy(&destination, &source, 14);
      
          printf("%s\n", destination);
          return 0;
      }
      

      https://godbolt.org/z/Z_yyJX

      【讨论】:

        【解决方案3】:
        #include <stdio.h>
        #include <string.h>
        
        int main()
        {   
            char source[] = "Hello, World!"; // <<-- let the compiler do the counting
            char destination[sizeof source]; // <<-- let the compiler do the counting
        
            strcpy(destination, source);
        
            /* equivalent to:
              memcpy(destination, source, sizeof source);
            */
        
            printf("%s\n", destination);
            return 0;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-06-06
          • 2011-07-09
          • 2015-08-22
          • 2012-08-15
          • 2010-10-27
          • 2015-03-29
          • 1970-01-01
          相关资源
          最近更新 更多