I want to merge 2 arrays into 1. For example:
- A1= 1,1
- A2= 2,2
- then A3 = 1,2,1,2
For example:
- A1= 1
- A2= 2,2,2,2
- then A3 = 1,2,2,2,2
For example:
- A1= 1,1,1,1
- A2= 2,2
- then A3 = 1,2,1,2,1,1
In last example, when I ran my code, I got 1,2,1,2,1,20.
In the second last, I got 1,2,32767,2,2.
So I guess I have a wrong code. Right after the I finished taking the element of the shorter array and fill up all the rest of the A3 with whoever is longer. But I couldn’t figure out why — can you help me?
code:
int *p3=arr3; //arr3 is A3 for example, arr1 = A1..etc, all sizes are defined
int index;
int index1=0;
int index2=0;
for(index = 0; index< sizeofArr3 ; index++)
{
if(index%2==0)
{
if(index1<=sizeofArr1)
*(p3++) = arr1[index1++];
else
*(p3++) = arr2[index2++];
}
else
{
if(index2<=sizeofArr2)
*(p3++) = arr2[index2++];
else
*(p3++) = arr1[index1++];
}
}
It’s this line:
and the equivalent one for
index2andsizeofArr2. You should be using<rather than<=.The reason has to do with C’s zero-based arrays. For an array of size
N, the element indexes are0throughN-1inclusive. Because you’re allowing it to access elementN(theN+1th element), you’re actually invoking undefined behaviour.Theoretically, the implementation can do anything in that case, up to and including destruction of the universe. I guess you’re lucky that it just decided to give you results that were slightly awry 🙂