Tuesday, 20 August 2013

a function to do deep copy for given node structure by C++

a function to do deep copy for given node structure by C++

I am designing a method that takes a pointer to a Node structure as a
parameter and returns a complete copy of the passed-in data structure. The
Node structure contains two pointers to other Node structures.
struct Node{
Node1 * p1;
Node2 * p2;
};
Node copyNode(struct Node *p)
{
try{
if (!p)
throw("input a NULL pointer");
}
catch(exception& e )
{
cout << e.what() << end;
}
Node * t = malloc(sizeof(*p));
t->p1 = malloc(sizeof(*(p->p1)));
memcpy(t->p1, p->p1);
t->p2 = malloc(sizeof(*(p->p2)));
memcpy(t->p2, p->p2);
return *t;
}
Is it correct ? Do I forget something ?
How to replace malloc with "new" ?
Any help would be appreciated !
thanks

No comments:

Post a Comment