为什么 memcpy 复制特征矩阵数据失败,而 std::copy 成功?
当我使用 Eigen 创建矩阵时,如下所示:
Eigen::MatrixXd M(3,3);
M<< 1.0, 4.0, 7.0, 2.0, 5.0, 8.0, 3.0, 6.0, 9.0 ;
std::cout<<M<<std::endl;
产生
1 4 7
2 5 8
3 6 9
我可以用指针遍历数据,打印每个元素:
double * d = M.data();
for(int i = 0;i<M.size();i++)
{
std::cout<<*d<<" ";
d++;
}
std::cout<<std::endl;
产生
1 2 3 4 5 6 7 8 9
我还可以使用 std::copy 将其复制到堆栈上相同类型的数组,然后打印该数组的元素:
double data_copy[9];
std::copy(M.data(),M.data()+M.size(),data_copy);
for(int i = 0;i<M.size();i++)
{
std::cout<<data_copy[i]<<" ";
}
std::cout<<std::endl;
生成
1 2 3 4 5 6 7 8 9
但是,我似乎无法使用 memcpy 进行等效的复制。这只能复制第一个元素:
double data_memcopy[9];
memcpy(data_memcopy,M.data(),M.size());
for(int i = 0;i<M.size();i++)
{
std::cout<<data_memcopy[i]<<" ";
}
std::cout<<std::endl;
产生
1 0 0 0 0 0 0 0 0
memcpy 没有执行我期望的操作的任何充分理由吗? (还是我使用不当?)
When I create a matrix using Eigen, like this:
Eigen::MatrixXd M(3,3);
M<< 1.0, 4.0, 7.0, 2.0, 5.0, 8.0, 3.0, 6.0, 9.0 ;
std::cout<<M<<std::endl;
produces
1 4 7
2 5 8
3 6 9
I can walk with a pointer through the data, printing each element:
double * d = M.data();
for(int i = 0;i<M.size();i++)
{
std::cout<<*d<<" ";
d++;
}
std::cout<<std::endl;
produces
1 2 3 4 5 6 7 8 9
I can also use std::copy to copy it to an array of the same type on the stack, then print the elements of that array:
double data_copy[9];
std::copy(M.data(),M.data()+M.size(),data_copy);
for(int i = 0;i<M.size();i++)
{
std::cout<<data_copy[i]<<" ";
}
std::cout<<std::endl;
produces
1 2 3 4 5 6 7 8 9
However, I can't seem to use memcpy to do the equivalent copy. This only manages to copy the first element:
double data_memcopy[9];
memcpy(data_memcopy,M.data(),M.size());
for(int i = 0;i<M.size();i++)
{
std::cout<<data_memcopy[i]<<" ";
}
std::cout<<std::endl;
produces
1 0 0 0 0 0 0 0 0
Any good reason why memcpy is not doing what I expect it should? (Or am I using it improperly?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要乘以 double 的大小:
否则,您只是复制 M.size() 字节,并且每个 double 在您的计算机上都超过一个字节。
所以你可能只写入第一个和第二个双精度数(它们在你的系统上可能是 8 个字节,因为你成功复制了第一个双精度数,而第二个双精度数你可能只复制了一个字节,这可能是零)。
You need to multiply by the size of a double:
Otherwise, you are only copying M.size() bytes, and each double is more than one byte on your machine.
So you were probably only writing to the first and second doubles (they probably are 8 bytes on your system, since you copied the first one successfully, and the second double you only probably copied one byte which was likely zeros).