Using memcpy to copy a range of elements from an array

风流意气都作罢 提交于 2019-12-29 06:00:24

问题


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?


回答1:


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.




回答2:


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.




回答3:


memcpy(array, matrix+80, sizeof(double) * 10);


来源:https://stackoverflow.com/questions/3902215/using-memcpy-to-copy-a-range-of-elements-from-an-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!