memcpy() — Copy Bytes Threadsafe: Yes. The memcpy() function copies count bytes of src to dest . The behavior is undefined if copying takes place between objects that overlap. The memmove() function allows copying between objects that might overlap.
memmove() is similar to memcpy() as it also copies data from a source to destination. memcpy() leads to problems when source and destination addresses overlap as memcpy() simply copies data one by one from one location to another.
If you are going to copy bytes (which I usually don't) std::memcpy is fine by my standard. My advice is never to use std::memcpy for any purpose. If you want to copy bytes, use std::copy . If you want to copy bytes in an implementation-specific way, use std::copy and the appropriate cast to warn others.
I always prefer the syntax
memcpy( &dst[dstIdx], &src[srcIdx], numElementsToCopy * sizeof( Element ) );
Just add the offset you want to the address of the buffer.
char abuff[100], bbuff[100];
....
memcpy( bbuff, abuff + 5, 10 );
This copies 10 bytes starting at abuff[5] to bbuff.
Just add the offset to the addresses. For example, if you wanted to copy the buffer starting with the Nth byte:
memcpy( destination, source + N, sourceLen - N );
This will copy to the destination
. If you also want to offset the destination - add the offset to both:
memcpy( destination + N, source + N, sourceLen - N );
An index is not required because you can simply update the source pointer by the specified number of bytes. The following wrapper should do the trick
void* memcpy_index(void *s1, const void *s2, size_t index, size_t n) {
s2 = ((char*)s2)+index;
return memcpy(s1, s2,n);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With