-3

I'm still having trouble understanding how to copy structs that include char* fields\other struct fields:

typedef struct node{
   int id;
   struct node* parent
   char * nodeName;
   struct node* nodes[100];
 }NODE,*pNODE;

I want to use this function : pNODE copyNode(pNODE oldNode) 1. i know that first I should do allocation for the new pointer data , and do the followong:

pNODE newNode = (pNODE)calloc(1,sizeof(NODE));
newNode.id=oldNode.id
//for the string that I want to copy I should allocate and use strcpy - in order not to point at the same string

but now I'm lost regarding the parent node, how do I copy it ? if I just do : newNode.parent=oldNode.parent I point at the same parent object, and if I change it's Id for example - it will change both the id of newNode and oldNode. how can I copy it?? without pointing at the same one? and how can i copy the pointer array??

thank you!

user1391863
  • 137
  • 3
  • 12
  • IMO, if you're wanting to deep copy like that, something you're doing is *very wrong*. You might want to think about: What do you want to do with the `parent`'s `parent`? You want that copied too? And what do you want done when the array of `nodes` is copied? You want their `nodes` arrays to be copied too? – ArjunShankar Aug 06 '12 at 08:31
  • 3
    Even a single day hasn't passed since you asked the exact same question. –  Aug 06 '12 at 08:40
  • 3
    possible duplicate of [How to duplicate a struct with char* and point on it?](http://stackoverflow.com/questions/11816406/how-to-duplicate-a-struct-with-char-and-point-on-it) –  Aug 06 '12 at 08:40

1 Answers1

2

Take a look at the memcopy function:

memcpy(oldNode.parent, newNode.parent, sizeof(node)).

Of course, you first need to allocate memory for the newNode's parent, using malloc (calloc doesn't make sense in this context - it's used for arrays)

newNode.parent = (NODE*)malloc(sizeof(NODE))

If you want to do a deep-copy (i.e. don't reuse referenced objects), you should go through the newNode struct and allocate memory for each pointer contained in the struct and then apply memcopy.

Razvan
  • 9,925
  • 6
  • 38
  • 51
  • 1
    While you're right about `calloc` not making sense here, the reason you state (used for arrays) might not be very accurate. `calloc` initializes allocated memory to 0s (to me, this is the bigger difference between `malloc` and `calloc`). – ArjunShankar Aug 06 '12 at 08:50
  • Ok, got your point. void * calloc ( size_t num, size_t size ); Allocates a block of memory for an array of num elements, each of them size bytes long, and initializes all its bits to zero So, i think it's primary purpose is to allocate arrays. – Razvan Aug 06 '12 at 08:52
  • 2
    Erm, if you insist, then sure. (But have a look at [this](http://stackoverflow.com/q/1538420/274261). Most people seem to care more about the 0's done by `calloc`.) – ArjunShankar Aug 06 '12 at 08:57