【发布时间】:2014-07-21 12:37:11
【问题描述】:
两个独立的程序运行几乎相同的代码。我将一个 int、enum 和 4 个浮点数复制到一个 unsigned char 缓冲区中,然后将它们读回以确保过程正确。
第一个是一个简单的测试程序,可以在here找到。
它产生这个输出:
id: 10
o: 2
one: 1
two: 2
three: 3
four: 4
---
id: 10
o: 2
one2: 1
two2: 2
three2: 3
four2: 4
所以我想,好吧...我可以把它移到实际的程序中。主程序可以在here找到。几乎一样吧?这就是问题所在:从缓冲区读取回一个变量是有问题的:
id: 1
o: 1
p1x: 1
p1y: 2
p2x: 3
p2y: 4
---
id: 1
o: 1073741824
one: 3
two: 4
three: 2.76624e+19
four: 4
由于某种原因,随着值被读出...memcpy 改变了不止一个变量的值,我最终搞砸了:
memcpy(&i2,&buffer[0],4); //sets i2 correctly to 1
memcpy(&o2, &buffer[4],4); //sets o2 correctly to DISTANCE (enum == 1)
memcpy(&one,&buffer[8],8); //resets o2 to 1073741824 and one to 1
memcpy(&two,&buffer[16],8); //sets two correctly to number 2, but one to 3
memcpy(&three,&buffer[24],8); //sets three correctly to 3, but two to 4
memcpy(&four,&buffer[32],8); //sets three to 2.766... and four to 4
std::cout << "id: " << i2 << std::endl;
std::cout << "o: " << o2 << std::endl;
std::cout << "one: " << one << std::endl;
std::cout << "two: " << two << std::endl;
std::cout << "three: " << three << std::endl;
std::cout << "four: " << four << std::endl;
更改 memcpy 以使用 sizeof() 修复它:
memcpy(&i2,&buffer[0],sizeof(i2));
memcpy(&o2, &buffer[4],sizeof(o2));
memcpy(&one,&buffer[8],sizeof(one));
memcpy(&two,&buffer[16],sizeof(two));
memcpy(&three,&buffer[24],sizeof(three));
memcpy(&four,&buffer[32],sizeof(four));
----
id: 1
o: 1
p1x: 1
p1y: 2
p2x: 3
p2y: 4
---
id: 1
o: 1
one: 1
two: 2
three: 3
four: 4
这里到底发生了什么??
【问题讨论】:
-
如果没有
buffer的声明及其与变量i2、o2等的关系,就无法判断。
标签: c++ char buffer sizeof memcpy