我对 C 中的深层复制有疑问。
我无法分享真实的代码,但我的代码看起来像这样:
struct a {
char *t1;
char *t2;
int a;
int b;
};
我有一个 struct a 类型的
s1
,其值是动态分配的。我有另一个结构 s2
我想将 struct a
的内容复制到其中。由于我有指针,所以我需要进行深复制,这样当我free(struct s1)
时我就不会丢失值。
为了进行深度复制,最后,我动态分配了结构
s2
,如下所示:
struct s2 = malloc(sizeof(struct a));
现在在另一个函数中,我使用
memmove
将 s1
的内容复制到 s2
:
memmove(s1.t1, &s2.t1, length_of_t1)
这是进行深复制的正确方法吗?
您可能想要这个:
struct a {
char *t1;
char *t2;
int a;
int b;
};
...
// assuming s1 points to a valid struct a
// and s1->t1 and s1->t2 point to valid C strings
struct *s2 = malloc(sizeof(struct a)); // allocate new struct
memcpy(s2, s1, sizeof(struct a)); // copy the struct
s2->t1 = malloc(strlen(s1->t1) + 1); // allocate space for t1
memcpy(s2->t1, s1->t1); // copy the bytes
s2->t2 = malloc(strlen(s2->t2) + 1); // allocate space for t2
memcpy(s2->t2, s1->t2); // copy the bytes
顺便说一句:我使用
memcpy
,因为源和目标之间没有重叠。
Discalimer:这是未经测试的代码,为简洁起见,省略了错误检查。