Shallow copy and deep copy in C

前端 未结 2 1385
暖寄归人
暖寄归人 2020-12-05 05:49

I tried googling this but only objected oriented languages pop up as results.

From my understanding a shallow copy is copying certain members of a struct.

so

2条回答
  •  囚心锁ツ
    2020-12-05 06:29

    No. A shallow copy in this particular context means that you copy "references" (pointers, whatever) to objects, and the backing store of these references or pointers is identical, it's the very same object at the same memory location.

    A deep copy, in contrast, means that you copy an entire object (struct). If it has members that can be copied shallow or deep, you also make a deep copy of them. Consider the following example:

    typedef struct {
        char *name;
        int value;
    } Node;
    
    Node n1, n2, n3;
    
    char name[] = "This is the name";
    
    n1 = (Node){ name, 1337 };
    n2 = n1; // Shallow copy, n2.name points to the same string as n1.name
    
    n3.value = n1.value;
    n3.name = strdup(n1.name); // Deep copy - n3.name is identical to n1.name regarding
                               // its *contents* only, but it's not anymore the same pointer
    

提交回复
热议问题