4

I am trying to memcpy from one ptr to another. I know the size that I want to copy. Both the destination and source pointers are void pointers. Is this valid? Does it actually copy the ELEMENT_SIZE (integer like 128) from source to the destination? I know this is not the most ideal thing to do. But I want to know if this works.

memcpy(to_add, element_ptr, ELEMENT_SIZE);
277roshan
  • 354
  • 1
  • 3
  • 13
  • 1
    Yes it works. It behaves the same as looping character pointers over that number of bytes. – M.M Sep 30 '16 at 04:58
  • 2
    Why would you think it would not work considering that `memcpy` is defined to accept void pointers? – kaylum Sep 30 '16 at 04:59
  • Give it a try. If it doesn't work the you expect it to work, come back to SO with a [mcve]. – R Sahu Sep 30 '16 at 05:02

3 Answers3

3

Does it actually copy the ELEMENT_SIZE (integer like 128) from source to the destination?

Yes, If you know the size information,then its working fine.

See the reference link : http://www.cplusplus.com/reference/cstring/memcpy/

msc
  • 33,420
  • 29
  • 119
  • 214
3

Parameter descriptions for memcpy from the documentation:

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 simply takes num bytes starting from the address source and copies them to memory starting at address destination.

A pointer is a fixed length memory address, regardless of type. It does not matter whether the pointer is char * (points to character data), int * (points to integer data), or void * (points to data of unknown type), it still just points to memory.

Because memcpy copies an explicit number of bytes, the type of data being pointed to is irrelevant; it just need memory addresses to data.

Stewart Smith
  • 1,396
  • 13
  • 28
0

It does not matter what pointer it is really. It is a very plain process of having two memory addresses and engaging a copy.

Armen Avetisyan
  • 1,140
  • 10
  • 29