【发布时间】: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