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

后端 未结 6 1859
故里飘歌
故里飘歌 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:19

    Instead of thinking about it as a copy, why don't you create a new struct but with the same parameters as the one you want to duplicate? It is a subtle difference but, you have the code already:

    Student *s2 = create_Student("Leeroy","Jenkins",50,1337);
    Student *wiper = create_Student(s2->first_name, s2->last_name, 
                                                   s2->grade, s2->id);
    

    the wiper struct has a clone of s2.

    To make a shallow copy, do as you are doing with s1 and s2 (the memcpy), or simply:

    s2 = malloc(sizeof(Student));
    *s2 = *s1
    

提交回复
热议问题