Making a deep copy of a struct…making a shallow copy of a struct

后端 未结 6 1973
故里飘歌
故里飘歌 2021-02-01 07:46

There are questions LIKE this one, but they are not similar enough to my specific question FOR ME to pick up on.

My question is about how to make a deep copy of a struct

6条回答
  •  终归单人心
    2021-02-01 08:18

    Instead of this:

    newStudentp -> last_name = (malloc((strlen(last_name) + 1)  * sizeof(char)));
    

    do:

    newStudentp -> last_name = strdup (last_name);
    

    Your deep copy wants to do something similar (not exactly what cnicutar suggested):

    s2->first_name = strdup (s1->first_name);
    

    The problem with cnicutar's suggestion is that it needs to manually allocate the buffer before the strcpy.

    And if I remember correctly:

    *s2 = *s1;

    will do a shallow copy.

    Of course, in both the deep and shallow copies you must make sure that you free the destination pointers, otherwise you'll get a memory leak. But even freeing the pointers can lead to problems if you deep copy to a structure that was previously shallow copied to.

提交回复
热议问题