C:深度复制 - 具有 void 指针的结构
我有一个以下结构
struct teststruct
{
int *a;
void *data;
};
是否可以对包含 void 指针的结构进行深层复制?我假设我无法判断 data
指针指向多少字节?所以我不能 malloc 指定的字节数并执行 memcpy。我说得对吗?
I've got a following struct
struct teststruct
{
int *a;
void *data;
};
Is it possible to do a deep copy of structure which contains a void pointer? I assume that I cannot tell how many bytes data
pointer points to? So I cannot malloc specified number of bytes and do memcpy. Am I right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不。由于您不知道 void* 指向的类型,因此不可能进行深层复制。
此外,您甚至无法深度复制
a
,因为它可能指向单个int
或它们的数组。通常在 C 中,如果您希望能够进行深层复制,您将拥有一个包含其内容的数据类型的结构。例如:
那么你可以使用
a_sz
来计算a
指向的内存由多少个整数组成以及data
的枚举类型,尽管从技术上讲它也可能是一个数组,因此您可能还需要一个d_sz
。另一个技巧是让
data
指向一个嵌入了自身数据类型的结构,例如:No. Since you do not know the type that the void* points to, a deep copy is out of the question.
In addition, you could not even deep copy
a
since it may point to either a singleint
ot an array of them.Typically in C, you would have a structure which carries the data types of it's contents if you wished to be able to do deep copies. For example:
Then you could use
a_sz
to figure out how many integers the memory pointed to bya
was composed of and the enumerated type ofdata
, although technically it could also be an array so you may need ad_sz
as well.Another trick is to have
data
point to a structure that carries it's own data type embedded in it, such as:如果您没有关于 void *data 指向的数据大小的信息,我会说您无法成功深度复制此结构。
If you have no information on the size of the data pointed to by
void *data
I would say you cannot successfully deep copy this struct.你是对的,你无法知道为
data
分配了多少字节。事实上,您甚至无法确定data
是否指向malloc()
ed 内存;它可以指向堆、堆栈或全局空间中的任何内容。即使您可以找出数据的大小,您仍然无法知道内部数据的结构,这意味着不可能进行适当的“深复制” 。深层复制不会停止在第一个指针深度。
You are correct, you cannot tell how many bytes have been allocated for
data
. In fact, you can't even be sure thatdata
points tomalloc()
ed memory; it could be pointing to anything on the heap, stack, or global space.Even if you could find out the size of the data, you still cannot know the structure of the internal data, which means that a proper "deep copy" would not be possible. A deep copy wouldn't stop at the first pointer depth.
你是对的,但请区分:你可以进行深层复制,但你无法知道指针指向多少字节。
You are right, but please distinguish: you can make a deep copy, but you can not tell on how many bytes pointer points to.