使用memcpy将数组复制到新的数组

时间:2018-02-21 20:11:16

标签: c arrays memory-management

我有一个问题,即我使用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;
}

2 个答案:

答案 0 :(得分:3)

不是分配内存并将其分配给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);
}

答案 1 :(得分:1)

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));
相关问题