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

memcpy copied wrong data from tail of array

我对 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)之外,我的所有变量都取真值。我试图改变尺寸,但没有成功。我想念的重点是什么?

您的编译器似乎将 unsigned long 视为 64 位数量,但 Win32 API 将 DWORD 定义为无符号的 32 位值。尝试:

typedef uint32_t DWORD;