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

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

    The difference between a shallow copy and a deep copy can be explained in one sentence: A shallow copy copies pointers; a deep copy copies what they point to.

    To start with the last part of your question: if there are no pointers, there's no difference between a shallow or a deep copy.

    Your attempt to make a shallow copy is technically correct. It's logically wrong, though. Your delete_student() function (the one that frees the mallocs) can't deal with shallow copies. It wouldn't know how many other student copies are still around, and ou'd need to delay the free() until the deletion of the alst copy.

    The deep copy has a very related problem. it's technically incorrect. Strangely enough, your create_student function shows that you do know how to copy a char* to another one - that has a deep copy of both first_name and last_name. Your copy_Student should do the same.

提交回复
热议问题