【发布时间】:2013-10-12 15:33:17
【问题描述】:
我正在尝试将我的结构转换为 char*,然后再转换回结构。但我想我错过了一些东西。一旦返回给struct,struct只有一个属性是正确的。其余的都是错误的。这是我的代码。
#include <iostream>
using namespace std;
struct INFO {
unsigned char a;
int b;
int c;
char g[121];
}inf;
int main () {
char frame[128];
INFO test1 = INFO();
test1.a='y';
test1.b=4000;
test1.c=9000;
strcpy(test1.g, "Goodbye World");
sprintf(frame,(char*)&test1);
INFO test2 = INFO();
memcpy((char*)&test2, frame, sizeof(frame)); //shouldn't test2 have test1 values?
cout << test2.a<<"\n";
cout << test2.b<<"\n";
cout << test2.c<<"\n";
cout << test2.g<<"\n";
getchar();
return 0;
}
输出:
y
-858993460
-858993460
╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
只有 test2.a 是正确的。我将其转换为 char* 是错误的,还是我将其转换回来的方式?谢谢
【问题讨论】:
-
除了可怕之外,您最好同时考虑所涉及的填充,然后将
frame声明为char frame[sizeof(struct INFO)];实际上,print 顶部的大小你的程序,只是为了踢。您还使用了sprintf(),“打印”到frame是完全错误的。当它遇到零字节时,它将停止发送数据(b和c中有大量零字节)。最后,我对未使用的全局变量inf的用途的好奇心正在杀死我。 -
sprintf 不是内存副本
-
snprintf(output,payloadsize , "%d%d%d%d",i,j,k,l)
-
╠ 在代码页 437 中为 0xCC,MSVC fills 0xCC to uninitialized memory to help debugging。这意味着您访问了未初始化的内存。你可以在这里找到关于 ╠ 和 0xCC 的大量问题