memcpy从数组尾部复制了错误的数据

时间:2018-02-07 23:15:07

标签: c++ memcpy

我的memcpy功能有问题。我尝试从char数组中复制部分数据,但我没有成功。

// Types
typedef unsigned char BYTE;
typedef unsigned short WORD;
typedef unsigned long DWORD;

// My variables
WORD bfType;
DWORD bfSize;
WORD bfReserved1;
WORD bfReserved2;
DWORD bfOffBits;

// My Func
void BmpFileHeader::setFileHeader(char* header)
{
    // header -> 42 4D BB E6 00 00 00 00 00 00 36 00 00 00
    char* pointerOfHeader = header;
    std::memcpy(&bfType, header, sizeof(WORD));
    pointerOfHeader+=2;
    std::memcpy(&bfSize, pointerOfHeader, sizeof(DWORD));
    pointerOfHeader+=4;
    std::memcpy(&bfReserved1, pointerOfHeader, sizeof(WORD));
    pointerOfHeader+=2;
    std::memcpy(&bfReserved2, pointerOfHeader, sizeof(WORD));
    pointerOfHeader+=2;
    // This point, pointerOfHeader is 36(catched with debugging)
    std::memcpy(&bfOffBits, pointerOfHeader, sizeof(DWORD));
 }

bfOffBits外,我的所有变量都采用真值(例如7950260717192478774)。我试图改变大小,但我没有成功。我错过了什么意思?

1 个答案:

答案 0 :(得分:3)

好像您的编译器将DWORD视为64位数量,但Win32 API将typedef uint32_t DWORD; 定义为无符号32位值。尝试:

ruby -I. main.rb