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

Can memcpy be used to copy part of an array?

Let's 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 copy / memory / array manipulation tools available for use with c / C ++?

+3


source to share


2 answers


memmove()

serves for this purpose.

EDIT: memcpy()

works great. Either way, this is probably more optimistic.

In this example, the code will be something like this:



int array1[10] = {0,1,2,3,4,5,6,7,8,9};
int array2[5] = {0,0,0,0,0};

memmove(array2, array1 + 5 * sizeof(int), 5 * sizeof(int));

      

This will copy 5 lots int

from array1, position 5, to array2, position 0.

+1


source


Can memcpy be used to copy part of an array?

No, this is impossible in general. This can only be done when the type of the array elements has a trivial layout.

Let's 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

are trivial types, so it will work for this specific case:

int source[10] = { ::: };
int target[5];

std::memcpy( target, source + 5, 5 * sizeof(int) );

      

Are there other copy / memory / array manipulation tools available for use with c / C ++?



Of course, the entire set of algorithms in the C ++ standard library will work with arrays. You use pointers to the first and one of the last elements in the array as begin/end

iterators. Or if you are using C ++ 11 then simple 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 meta-trick you can use to check if a type is trivial and also to define such a thing: http://en.cppreference.com/w/cpp/types/is_trivial

+9


source







All Articles