简体   繁体   English

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

[英]memcpy copied wrong data from tail of array

I have a problem with memcpy function. 我有memcpy函数的问题。 I tried copy part of data from array of char but I was not success. 我尝试从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));
 }

All of my variables take true value except bfOffBits (example 7950260717192478774). bfOffBits外,我的所有变量都采用真值(例如7950260717192478774)。 I tried to change size but I was not succeed. 我试图改变大小,但我没有成功。 What is the point I am missing? 我错过了什么?

It appears as though your compiler is treating unsigned long as a 64-bit quantity, but the Win32 API defines DWORD as an unsigned 32-bit value. 看起来您的编译器将unsigned long整数视为64位数量,但Win32 API将DWORD定义为无符号32位值。 Try: 尝试:

typedef uint32_t DWORD;

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

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