问题描述
我的C程序中有以下结构
I have the following struct in my C program
struct person {
char key[50];
char color[20];
int age;
};
我想对该结构进行深层复制。我已经完成了深层复制功能的设置,但是对于如何深层复制字符串有些困惑。我听说有人使用 strcpy
,其他人使用 strdup
。
I want to make a deep copy of this struct. I've got my deep copy function setup however I'm a bit confused about how to deep copy strings. I've heard of people using strcpy
and others using strdup
.
我要在程序中执行的操作是,如果释放原始人员,则不会影响深度复制人员的键和颜色。设置后,键和颜色将无法更改。就我而言,我应该使用 strcpy
还是 strdup
函数?
What I want in my program is for the deep copied person's key and color not to be affected if the original person is freed. Once set, the key and color cannot change. For my purpose, should I be using the strcpy
or strdup
function?
推荐答案
strcpy()
和 strdup()$ c之间有区别$ c>。
-
strdup()
分配空间并返回指向字符串副本的指针,还必须 free()。
strdup()
allocates space and returns a pointer to the copy of the string, you also have tofree()
the returned pointer.
strcpy()
占用分配的空间并将字符串复制到其中。
strcpy()
takes the allocated space and copies the string into it.
在您的情况下,它似乎是 strcpy()
,因为结构的字段不是指针,因此您无法为它们分配指向已分配空间的指针,是 strdup()
返回的结果。
It seems that in your case it's strcpy()
because the fields of your structure are not pointers so you can't assign to them a pointer to allocated space which is what strdup()
returns.
但是,如您实际上不需要这样做的答案。
However, as explained in this answer you actually don't need to.
这篇关于使用C中的char数组进行深度复制结构(如何复制数组?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!