Is it possible to use memcpy to copy part of an array?
Say for example we have an array of 10 integers. Can we create a new array, and copy the last 5 integers into it?
Are there other memory/array copying/manipulation tools which are available for use with c/c++?
Memcpy copies data bytes by byte from the source array to the destination array. This copying of data is threadsafe.
memcpy() function in C/C++ The function memcpy() is used to copy a memory block from one location to another. One is source and another is destination pointed by the pointer. This is declared in “string.
In the C Programming Language, the memcpy function copies n characters from the object pointed to by s2 into the object pointed to by s1. It returns a pointer to the destination. The memcpy function may not work if the objects overlap.
memmove() is similar to memcpy() as it also copies data from a source to destination.
Is it possible to use memcpy to copy part of an array?
No, it is not possible in the general case. You can only do that when the type of the elements in the array is of trivial layout.
Say for example we have an array of 10 integers. Can we create a new array, and copy the last 5 integers into it?
int
s are trivial types, so for that particular case it would work:
int source[10] = { ::: };
int target[5];
std::memcpy( target, source + 5, 5 * sizeof(int) );
Are there other memory/array copying/manipulation tools which are available for use with c/c++?
Sure, the entire set of algorithms in C++ Standard Library will work with arrays. You use pointers to the first and one-past-the-last elements in the array as begin/end
iterators. Or if you are using C++11 then just std::begin|end( array )
.
std::copy( source + 5, source + 10, target + 0 );
or
std::copy( std::begin(source) + 5, std::end(source), std::begin(target) );
Here is a metafunction you can use to check whether a type is trivial, along with the definition of such concept: http://en.cppreference.com/w/cpp/types/is_trivial
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