18

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?

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
Eminemya
  • 379
  • 1
  • 6
  • 15

3 Answers3

25

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.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
16
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.

aschepler
  • 70,891
  • 9
  • 107
  • 161
  • 5
    One advantage of using the `matrix + N` instead of `&matrix[N]` is that for an array of size `M`, `matrix + M` is allowed but `&matrix[M]` is not (because the latter dereferences a pointer to the element one-past-the-end). – James McNellis Oct 10 '10 at 21:47
11
memcpy(array, matrix+80, sizeof(double) * 10);
lennon310
  • 12,503
  • 11
  • 43
  • 61
Daryl Hanson
  • 448
  • 2
  • 7