我试图将我的结构转换为char*,然后返回到结构.但我想我错过了一些东西.一旦它返回到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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
y
-858993460
-858993460
????????????????????????????????????????????????????????????????????????????????
????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)
只有test2.a是正确的.我将它转换为char*错误,还是我将其转换回来的方式?谢谢
这段代码存在一些问题,但导致问题的是使用sprintf将二进制数据从结构复制到字符数组:如果结构数据中的任何地方都有NUL字节,则副本将停止.在这种情况下,在第一个成员之后的struct数据中有一个NUL char,嵌入在第二个成员中或者由于填充,因此只有第一个成员被完全复制.
用memcpy而不是sprintf.
// sprintf(frame,(char*)&test1); <-- wrong
memcpy(frame, &test1, sizeof(frame));
INFO test2 = INFO();
memcpy(&test2, frame, sizeof(frame));
Run Code Online (Sandbox Code Playgroud)
另一个问题是由于填充和对齐,INFO结构的大小可能不是128,所以它不能完全复制到frame.使用sizeof运算符查找大小.
| 归档时间: |
|
| 查看次数: |
22118 次 |
| 最近记录: |