I have an issue where i'm using memcpy() to copy an array to a new array with dynamic memory. And my question is why there is 3 zeros between the numbers? like my original array is a1[] ={1, 2, 3, 4, 5} and when I use memcpy(mem1,a1,n1) then my mem1 will be 1 0 0 0 2 ?
Here's my code:
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;
}