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

后端 未结 6 1870
故里飘歌
故里飘歌 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条回答
  •  猫巷女王i
    2021-02-01 08:19

    The code you have listed as making a shallow copy isn't; it will actually smash the stack and probably crash the program.

    Student *s1 = create_Student("Bo","Diddly", 100, 221);
    Student *s2 = create_Student("Leeroy","Jenkins",50,1337);
    memcpy(&s2,&s1,sizeof(Student)); //shallow copy of s1 INTO s2?
    

    If you had the size right, that would be the same as s2 = s1;. But since you have the size wrong, it is copying too much and will overwrite whatever is in memory after s2. To do a real shallow copy, leave off the &:

    memcpy(s2,s1,sizeof(Student)); //shallow copy of s1 INTO s2
    

    The code you have for a deep copy is similarly wrong, but you're on the right track. The basic idea behind a deep copy is that you have to copy each field; for non-pointer types this is the same as a shallow copy, but for pointers you have to do something smarter. The code you posted, however, isn't doing that. Try this instead.

    void copy_Student(Student *s1, Student *s2)
    {
        s2 -> grade = s1 -> grade;
        s2 -> id = s2 -> id;
        s2 -> first_name = strdup(s1 -> first_name);
        s2 -> last_name = strdup(s1 -> last_name);
    }
    

    Note that to avoid memory leaks, you would also need to free the old names from s2 before assigning the new copies, make a free_Student function that would free these names, and also make sure that create_Student copies the names in the first place (or else include "should free" flags so you don't have to copy literal strings).

    Now, for a struct without pointers (or other reference types), there is no difference between a deep and a shallow copy because the data structure it itself shallow.

提交回复
热议问题