Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using memcpy to copy a range of elements from an array

Tags:

c++

memcpy

Say we have two arrays:

double *matrix=new double[100];
double *array=new double[10];

And we want to copy 10 elements from matrix[80:89] to array using memcpy.

Any quick solutions?

like image 355
Eminemya Avatar asked Oct 10 '10 21:10

Eminemya


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.

Is memcpy faster than for loop C?

A simple loop is slightly faster for about 10-20 bytes and less (It's a single compare+branch, see OP_T_THRES ), but for larger sizes, memcpy is faster and portable.

What can I use instead of memcpy?

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

Is memcpy inefficient?

memcpy is usually naive - certainly not the slowest way to copy memory around, but usually quite easy to beat with some loop unrolling, and you can go even further with assembler.


2 Answers

It's simpler to use std::copy:

std::copy(matrix + 80, matrix + 90, array);

This is cleaner because you only have to specify the range of elements to be copied, not the number of bytes. In addition, it works for all types that can be copied, not just POD types.

like image 119
James McNellis Avatar answered Sep 18 '22 20:09

James McNellis


memcpy(array, &matrix[80], 10*sizeof(double));

But (since you say C++) you'll have better type safety using a C++ function rather than old C memcpy:

#include <algorithm>
std::copy(&matrix[80], &matrix[90], array);

Note that the function takes a pointer "one-past-the-end" of the range you want to use. Most STL functions work this way.

like image 23
aschepler Avatar answered Sep 20 '22 20:09

aschepler