简体   繁体   中英

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:

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*".

Can somebody help? I don't want to use a for-next-statement to copy my values over. I would like to use MemCpy if possible because I think it is the fastest way.

Thank you!

The 2nd argument to memcpy needs to be an address:

&m_data_content_joinfeatures[iByteStartPos]

Also, the name iByteStartPos seems to imply byte offset into the vector. The code you wrote (once fixed to include & ) will copy starting from the iByteStartPos double in the vector. 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:

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 .

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 .

Something like:

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

should solve this error.

But why don't you use std::copy ?

With С++11 you can do

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

or even shorter

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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