C++ memcpy : double incompatible with const void

标签 c++ vector struct memcpy

我有一个私有(private)成员(member)

vector<double>m_data_content_joinfeatures;

和一个结构:

struct udtJoinFeatures
{
    double Values[16];
};

我现在想将一些值从 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);
}

但是编译器告诉我“double 与 void* 类型的参数不兼容”。

有人可以帮忙吗?我不想使用 for-next-statement 来复制我的值。 如果可能,我想使用 MemCpy,因为我认为这是最快的方法。

谢谢!

最佳答案

memcpy 的第二个参数需要是一个地址:

&m_data_content_joinfeatures[iByteStartPos]

此外,名称 iByteStartPos 似乎暗示了 vector 中的 byte 偏移量。您编写的代码(一旦固定为包含 &)将从 vector 中的 iByteStartPos double 开始复制。如果你真的想要一个字节偏移量,你需要将数据开始转换为const char *并用指针算法计算地址:

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

但是一旦您的代码开始看起来像那样,最好重新考虑您的策略并放弃 memcpy 和基于字节的索引,将它们替换为更安全的高级 API,例如 std::copy.

关于C++ memcpy : double incompatible with const void,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18812250/

相关文章:

c++ - 从另一个类访问静态成员函数

c++ - 返回 std:vector 与 std::async c++11

多次调用函数中的c++大 vector

c - 如何修复错误: incompatible types when returning type 'struct {aka struct <anonymous>}

c++ - 声明数组导致错误

c++ - 我是否正确删除了指向对象的指针 vector ?

c++ - std::vector resize() 仅在clear() 之后才起作用

go - 使用类型取决于 bool 值的全局范围初始化结构

双重访问查找操作所需的结构的 C++ 容器

c++ - C++ 中类似 Python 的动态参数解包?