unsigned long id = 12;
unsigned long age = 14;
unsigned char* pData = new unsigned char[8];
memcpy(pData,&id,4);/* using memcpy to copy */
pData = pData + 4;
memcpy(pData,&age,4);/* using memcpy to copy */
std::cout<<*reinterpret_cast<unsigned long*>(pData)<<std::endl;
pData = pData - 4;
std::cout<<*reinterpret_cast<unsigned long*>(pData)<<std::endl;

在Linux上输出



Windows(vc++)上的

最佳答案

您假设sizeof(unsigned long)始终为4。这是不正确的。

试试这个:

const size_t NBYTES = sizeof(unsigned long);
unsigned long id = 12;
unsigned long age = 14;
unsigned char* pData = new unsigned char[2 * NBYTES];
memcpy(pData,&id, NBYTES);/* using memcpy to copy */
pData = pData + NBYTES;
memcpy(pData,&age, NBYTES);/* using memcpy to copy */
std::cout<<*reinterpret_cast<unsigned long*>(pData)<<std::endl;
pData = pData - NBYTES;
std::cout<<*reinterpret_cast<unsigned long*>(pData)<<std::endl;

如果要使用显式数据大小,请使用<cstdint>中定义的类型。可以在here中找到文档。

关于c++ - Linux和Windows上的输出差异,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31130780/

10-11 08:30