简体   繁体   English

C ++ memcpy:与const void不兼容的双精度

[英]C++ memcpy: double incompatible with const void

I have a private member 我有一个私人会员

vector<double>m_data_content_joinfeatures;

and a struct: 和一个结构:

struct udtJoinFeatures
{
    double Values[16];
};

I would now like to copy some values from m_data_content_joinfeatures to a struct of udtJoinFeatures like this: 我现在想将一些值从m_data_content_joinfeatures复制到udtJoinFeatures的结构中,如下所示:

void clsMapping::FeedJoinFeaturesFromMap(udtJoinFeatures &uJoinFeatures)
{

    unsigned int iByteStartPos=1024; //where the data starts that I want to copy
    unsigned int iByteCount=128; //the number of bytes that I want to copy

    memcpy(&uJoinFeatures.Values[0], m_data_content_joinfeatures[iByteStartPos],iByteCount);
}

But the compiler tells me that "double is not compatible with the parameter of the kind void*". 但是编译器告诉我“ double与void *类型的参数不兼容”。

Can somebody help? 有人可以帮忙吗? I don't want to use a for-next-statement to copy my values over. 我不想使用for-next-statement复制我的值。 I would like to use MemCpy if possible because I think it is the fastest way. 我想尽可能使用MemCpy,因为我认为这是最快的方法。

Thank you! 谢谢!

The 2nd argument to memcpy needs to be an address: memcpy的第二个参数必须是一个地址:

&m_data_content_joinfeatures[iByteStartPos]

Also, the name iByteStartPos seems to imply byte offset into the vector. 另外,名称iByteStartPos似乎暗示向量中的字节偏移量。 The code you wrote (once fixed to include & ) will copy starting from the iByteStartPos double in the vector. 您编写的代码(一旦固定为包括& )将从向量中的iByteStartPos double开始复制。 If you really want a byte offset, you will need to convert the data start to const char * and calculate the address with pointer arithmetic: 如果您确实想要字节偏移量,则需要将数据开头转换为const char *并使用指针算法计算地址:

memcpy(&uJoinFeatures.Values[0],
       reinterpret_cast<const char*>(m_data_content_joinfeatures.data()) + iByteStartPos,
       iByteCount);

But once your code begins to look like that, it's a good idea to rethink your strategy and turn away from memcpy and byte-based indices, replacing them with safer high-level APIs such as std::copy . 但是,一旦您的代码开始看起来像这样,最好重新考虑您的策略并放弃基于memcpy和基于字节的索引,而用更安全的高级API(例如std::copy代替它们。

If you take a loop at memcpy , you will see that it needs a pointer as a second argument and your giving it a double . 如果您在memcpy处进行循环,则会看到它需要一个指针作为第二个参数,并给它double

Something like: 就像是:

 memcpy(&uJoinFeatures.Values[0], &m_data_content_joinfeatures[iByteStartPos],iByteCount);
 //                               ^

should solve this error. 应该解决这个错误。

But why don't you use std::copy ? 但是,为什么不使用std::copy呢?

With С++11 you can do 使用С++ 11,您可以

memcpy(&uJoinFeatures.Values[0], m_data_content_joinfeatures.data() + iByteStartPos, iByteCount);

or even shorter 甚至更短

memcpy(uJoinFeatures.Values, m_data_content_joinfeatures.data() + iByteStartPos, iByteCount);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM