I'm having the below issues whenever I run this program in Visual Studio.
#include <iostream>
using namespace std;
int* append(int*, int, int*, int);
int* merge(int*, int, int*, int);
void print(int*, int, const char*);
int main()
{
int arrayA[] = { 11,33,55,77,99 }; // use other values for more tests
int arrayB[] = { 22,44,66,88 };
print(arrayA, 5, "Sorted array A: ");
print(arrayB, 4, "Sorted array B: ");
int* arrayC = append(arrayA, 5, arrayB, 4); // arrayC points to the appended array
print(arrayC, 9, "Append B to A: ");
int* arrayD = merge(arrayA, 5, arrayB, 4);
print(arrayD, 9, "Merge A to B: ");
delete[] arrayC;
delete[] arrayD;
return 0;
}
int* append(int* arrayA, int sizeA, int* arrayB, int sizeB)
{
int num = sizeA + sizeB;
int* appendArray = new int[num];
for (int i = 0; i < sizeA; i++)
{
appendArray[i] = arrayA[i];
}
for (int i = sizeA - 1, j = 0; i < (sizeB + sizeA); i++, j++)
{
appendArray[i] = arrayB[j];
}
return appendArray;
}
int* merge(int* arrayA, int sizeA, int* arrayB, int sizeB)
{
int num = sizeA + sizeB;
int* mergeArray = new int[num];
int i = 0, j = 0, k = 0;
do
{
if (arrayA[i] <= arrayB[j])
{
mergeArray[k] = arrayA[i];
i++;
k++;
}
else
{
mergeArray[k] = arrayB[i];
j++;
k++;
}
} while (k < sizeof(mergeArray));
return mergeArray;
}
void print(int* array, int size, const char* lable)
{
cout << lable;
for (int i = 0; i < size; i++)
{
cout << array[i] << " ";
}
cout << endl;
}
This program currently outputs:
Sorted array A: 11 33 55 77 99
Sorted array B: 22 44 66 88
Append B to A: 11 33 55 77 22 44 66 88 -858993460
Merge A to B: 11 44 33 66 55 88 77 -858993460 -842150451
and I'm not really sure why.
The expected output is:
Sorted array A: 11 33 55 77 99
Sorted array B: 22 44 66 88
Append B to A: 11 33 55 77 99 22 44 66 88
Merge A to B: 11 22 33 44 55 66 77 88 99