浅拷贝和深拷贝用C [英] Shallow copy and deep copy in C

查看:170
本文介绍了浅拷贝和深拷贝用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试这个谷歌搜索,但只有反对面向语言弹出的结果。

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 lets say a struct is

typedef struct node
{
    char **ok;
    int hi;
    int yep;
    struct node *next;
}node_t

复制字符**会是一个浅拷贝

copying the char** would be a shallow copy

但复制整个链表将是一个深拷贝?

but copying the whole linked list would be a deep copy?

我是否有正确的想法还是我的方法了吗?谢谢你。

Do I have the right idea or am I way off? Thanks.

推荐答案

没有。浅表副本在这种特殊背景下意味着你​​复制参考(指针,等等)的对象,而这些引用或指针的后备存储是相同的,它在相同的内存位置非常相同的对象。

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

这篇关于浅拷贝和深拷贝用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆