My goal in this program is to take two user entered arrays of a given size and merge them into one.
I'm able to successfully enter both arrays' size and their elements, but it fails to output the merged array- giving me this error:
"Error in `./a.out': free(): invalid pointer: 0x0..."
I've tried to debug but to no avail, I can't seem to figure out if I have incorrect syntax or I'm making an incorrect call.
Any help appreciated
#include<iostream>
using namespace std;
int* mergeArrays(int[], int[], int, int);
int arr1[0], arr2[0];
int main()
{
int size1, size2, i;
cout<<"Enter the first array's size : ";
cin>>size1;
int *arr1 = new int[size1];
cout<<"Enter the first array's elements : ";
for(i=0; i<size1; i++)
{
cin>>arr1[i];
}
cout<<"Enter the second array's size : ";
cin>>size2;
cout<<"Enter the second array's elements : ";
for(i=0; i<size2; i++)
{
cin>>arr2[i];
}
delete[] arr1;
delete[] arr2;
cout << mergeArrays;
}
int* mergeArrays(int arr1[], int arr2[], int size1, int size2){
int i, k, size;
int size3 = size1 + size2;
int *mergeArr = new int[size3];
for(i=0; i<size1; i++)
{
mergeArr[i]=arr1[i];
}
size=size1+size2;
for(i=0, k=size1; k<size && i<size2; i++, k++)
{
mergeArr[i]=arr2[i];
}
cout<<"The merged array is: \n";
for(i=0; i<size3; i++)
{
cout<<mergeArr[i]<<" ";
}
return mergeArr;
}