memcpy 如何与 void 指针一起使用?
How does memcpy works with void pointers?
我正在尝试从一个指针到另一个指针进行 memcpy。我知道我要复制的尺寸。目标指针和源指针都是空指针。这有效吗?它实际上是否将 ELEMENT_SIZE(如 128 之类的整数)从源复制到目标?我知道这不是最理想的做法。但我想知道这是否有效。
memcpy(to_add, element_ptr, ELEMENT_SIZE);
实际上是什么指针并不重要。有两个内存地址,搞一个副本,很简单的过程。
Does it actually copy the ELEMENT_SIZE (integer like 128) from source
to the destination?
是的,如果您知道尺寸信息,那么它就可以正常工作。
参见参考 link : http://www.cplusplus.com/reference/cstring/memcpy/
文档中 memcpy
的参数说明:
void * memcpy ( void * destination, const void * source, size_t num );
destination
: Pointer to the destination array where the content is to be copied,
type-casted to a pointer of type void*.
source
: Pointer to the source of data to be copied, type-casted to a pointer of type const void*.
num
: Number of bytes to copy. size_t is an unsigned integral type.
memcpy
只是从地址 source
开始获取 num
个字节,并将它们复制到从地址 destination
开始的内存中。
指针是固定长度的内存地址,与类型无关。不管指针是char *
(指向字符数据),int *
(指向整数数据),还是void *
(指向未知类型的数据),它仍然只是指向内存。
因为memcpy
复制了一个明确的字节数,指向的数据类型是无关紧要的;它只需要数据的内存地址。
我正在尝试从一个指针到另一个指针进行 memcpy。我知道我要复制的尺寸。目标指针和源指针都是空指针。这有效吗?它实际上是否将 ELEMENT_SIZE(如 128 之类的整数)从源复制到目标?我知道这不是最理想的做法。但我想知道这是否有效。
memcpy(to_add, element_ptr, ELEMENT_SIZE);
实际上是什么指针并不重要。有两个内存地址,搞一个副本,很简单的过程。
Does it actually copy the ELEMENT_SIZE (integer like 128) from source to the destination?
是的,如果您知道尺寸信息,那么它就可以正常工作。
参见参考 link : http://www.cplusplus.com/reference/cstring/memcpy/
文档中 memcpy
的参数说明:
void * memcpy ( void * destination, const void * source, size_t num );
destination
: Pointer to the destination array where the content is to be copied, type-casted to a pointer of type void*.
source
: Pointer to the source of data to be copied, type-casted to a pointer of type const void*.
num
: Number of bytes to copy. size_t is an unsigned integral type.
memcpy
只是从地址 source
开始获取 num
个字节,并将它们复制到从地址 destination
开始的内存中。
指针是固定长度的内存地址,与类型无关。不管指针是char *
(指向字符数据),int *
(指向整数数据),还是void *
(指向未知类型的数据),它仍然只是指向内存。
因为memcpy
复制了一个明确的字节数,指向的数据类型是无关紧要的;它只需要数据的内存地址。