-2

I have a question. I have a struct with details in it. Then I have a node that contains the details of the struct. My question is, how do I copy the node to a new node with all the details in it?Can I do it like this?

    newNode = oldNode;

Or should I make it like this?

    newNode -> structName -> detail1 = oldNode -> structName -> detail1;
    newNode -> structName -> detail2 = oldNode -> structName -> detail2;

And so on. The details in struct are value type.Is there any other way? Thank you

terk
  • 15
  • 4
  • Are `detail1` and `detail2` value or pointer types? – marosoaie Apr 11 '14 at 17:19
  • 1
    show sample definitions for the struct and node. – AShelly Apr 11 '14 at 17:20
  • See: http://stackoverflow.com/questions/15278194/shallow-copy-and-deep-copy-in-c. It depends on what and how you want the copy. – Martin Apr 11 '14 at 17:21
  • Your first example just copies the pointer, so both pointers point to the same data. If you want a "real" copy, you'll have to do it the second way (applying the same idea to any pointers in the struct elements). – ooga Apr 11 '14 at 17:24

2 Answers2

1

Assuming your newNode & oldNode point to valid blocks in memory.

newNode = oldNode;

would mean you are pointing newNode to the same block where oldNode points to, which you don't want.

Instead, you can copy it the way you are doing by "copying" individual elements.

Or if you are copying entire "contents" of oldNode to newNode, you can use memcpy.

memcpy(newNode, oldNode, sizeof(newNode);
brokenfoot
  • 11,083
  • 10
  • 59
  • 80
1

If your node structure has this form

struct node
{
  int i;
  char c;       
};

then to copy elements of node1 to node2, just use node2=node1; That will copy contents of elements of node1 to node2.

However remember that only addresses get copied for pointers. Foe example, if the structure was:

struct node
{
  char *c;
};

then using node2=node1; will only copy the address held by the pointer node1.c. Any changes made using *node2.c will also affect *node1.c

tdk
  • 342
  • 1
  • 13