Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using memcpy to copy part of an array, and other memory manipulation tools

Tags:

c++

arrays

memcpy

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++?

like image 881
FreelanceConsultant Avatar asked Feb 07 '13 17:02

FreelanceConsultant


People also ask

Does memcpy copy an array?

Memcpy copies data bytes by byte from the source array to the destination array. This copying of data is threadsafe.

What is the use of memcpy?

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.

How does memcpy work in C?

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.

What can I use instead of memcpy?

memmove() is similar to memcpy() as it also copies data from a source to destination.


1 Answers

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?

ints 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

like image 168
K-ballo Avatar answered Nov 10 '22 18:11

K-ballo