【问题标题】:copying array to a new one with memcpy使用 memcpy 将数组复制到新数组
【发布时间】:2018-02-21 20:11:15
【问题描述】:

我有一个问题,我使用memcpy() 将数组复制到具有动态内存的新数组。我的问题是为什么数字之间有 3 个零?就像我的原始数组是 a1[] ={1, 2, 3, 4, 5} 而当我使用 memcpy(mem1,a1,n1) 那么我的 mem1 将是 1 0 0 0 2 ? 这是我的代码:

int join_arrays(unsigned int n1, int *a1, unsigned int n2, int *a2, unsigned 
int n3, int *a3)
{
    /*Here I just print the original a1 just to make sure it's correct*/
    for (int j = 0; j < 5; j++) {
        printf("%d  ", a1[j]);
    }
    /*I allocate the memory for the new array*/
    char *mem1;
    mem1 = malloc(n1*sizeof(int));

    /*checking if the allocation succeeded*/
    if (!mem1) {
    printf("Memory allocation failed\n");
    exit(-1);
    }

    /*Using memcpy() to copy the original array to the new one*/
    memcpy(mem1, a1, n1);

    /*Printing the new array and this print gives me "1 0 0 0 2"
      and it should give me "1 2 3 4 5"*/
    printf("\n");
    for (int i = 0; i < 5; i++) {
        printf("%d  ", mem1[i]);
    }
    return 0;
}
int main(void)
{
    /* these are the original arrays which I need to put together to a single array */
    int a1[] = { 1, 2, 3, 4, 5 };
    int a2[] = { 10, 11, 12, 13, 14, 15, 16, 17 };
    int a3[] = { 20, 21, 22 };

    /*The number of elements are before the array itself*/
    join_arrays(5, a1, 8, a2, 3, a3);


    return 0;
}

【问题讨论】:

    标签: c arrays memory-management


    【解决方案1】:

    不要分配内存并将其分配给char*,而是使用int* 并使用它。

    int *mem1;
    mem1 = malloc(n1*sizeof(int)); // malloc(n1 * sizeof *mem1);
    ..
    memcpy(mem1,a1,n1*sizeof(a1[0]));
    

    还要检查 malloc 是否失败 - 但添加适当的错误消息:-

    if (!mem1) {
       perror("Memory allocation failed\n");
       exit(EXIT_FAILURE);
    }
    

    在你的情况下不要忘记释放动态分配的内存

    free(mem1);
    

    正如你所说,你需要从函数中返回它,然后你会做这样的事情

    int *join_arrays(..){
    
      return mem1;
    }
    int main(void){
    
      int *p = join_arrays(..);
      /* work with it */
    
      free(p);
    }
    

    【讨论】:

    • 这很有效,但我的函数必须返回一个指向新数组 mem1 的指针,所以我还需要释放内存吗?
    • @michael.: 将添加到 answer..wait.
    • @michael.:已编辑。
    • 好吧,我就是这么想的!
    【解决方案2】:

    mem1 这里是 char 指针而不是 int 指针。

    因此,当您尝试打印 mem1[i] 时,它实际上会打印存储在地址 mem1+i 的字节,而不是 4 个字节。显然整数 1 在你的机器上是这样存储的:

     00000001 00000000 00000000 00000000
    

    这就是你得到 3 个零的原因。

    尝试将变量类型更改为int*,如下所示:

    int *mem1;
    mem1 = malloc(n1*sizeof(int));
    memcpy(mem1,a1,n1*sizeof(int));
    

    【讨论】:

      猜你喜欢
      • 2012-07-13
      • 1970-01-01
      • 2020-04-02
      • 2015-06-05
      • 1970-01-01
      • 2023-02-09
      • 2018-01-09
      • 2020-04-22
      • 2017-11-13
      相关资源
      最近更新 更多