arr1,arr2 are two arrays of pointers, I have to merge these into arr3. When the program gets arr3[1] (when k=1) the program is closes , I don't get why.
Please help.
class Node {
public:
Node* left;
T data;
Node* right;
int height;
};
void mergeArrays(Node<T>** arr1,Node<T>** arr2,int len1,int len2){
int p=0,q=0,k=0;
Node<T>** arr3 = new Node<T>*[len1 len2];
while ( p < len1 && q < len2) {
if ((arr1[p])->data< (arr2[q])->data) {
(arr3[k ])->data = (arr1[p ])->data;
} else {
(arr3[k ])->data = (arr2[q ])->data;
}
}
while ( p < len1) {
(arr3[k ])->data = (arr1[p ])->data;
}
while ( q < len2) {
(arr3[k ])->data = (arr2[q ])->data;
}
}
CodePudding user response:
You're not copying pointers. You're copying values from one data
member of some object to another data
member of some object. But the problem is, there is no "there" there to copy to . You allocate a bed of pointers for arr3
, but there are no objects behind those pointers so this:
(arr3[k ])->data = (arr1[p ])->data;
Invokes undefined behavior.
I'm fairly certain this is what you were shooting for:
template<class T>
Node<T>** mergeArrays(Node<T> **arr1, Node<T> **arr2, int len1, int len2)
{
int p = 0, q = 0, k = 0;
Node<T> **arr3 = new Node<T> *[len1 len2];
while (p < len1 && q < len2)
{
if ((arr1[p])->data < (arr2[q])->data)
{
arr3[k ] = arr1[p ];
}
else
{
arr3[k ] = arr2[q ];
}
}
while (p < len1)
{
arr3[k ] = arr1[p ];
}
while (q < len2)
{
arr3[k ] = arr2[q ];
}
return arr3;
}