将结构转换为字符*并返回

converting struct to char* and back

本文关键字:返回 字符 结构 转换      更新时间:2023-10-16

我正在尝试将我的结构转换为字符*,然后再转换为结构。但我想我错过了一些东西。一旦它返回到结构,结构只有一个属性是正确的。其余的都是错的。这是我的代码。

#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是正确的。是我错误地将其转换为字符*,还是我将其转换回来的方式?谢谢

此代码存在一些问题,但导致问题的问题是使用 sprintf二进制数据从结构复制到字符数组:如果结构数据中的任何位置存在 NUL 字节,则复制将停止。在这种情况下,结构数据中紧跟在第一个成员之后,嵌入在第二个成员中或由于填充而存在 NUL 字符,因此仅完全复制第一个成员。

使用 memcpy 而不是 sprintf

// sprintf(frame,(char*)&test1); <-- wrong
memcpy(frame, &test1, sizeof(frame));
INFO test2 = INFO();
memcpy(&test2, frame, sizeof(frame));

另一个问题是,由于填充和对齐,INFO结构的大小可能不是128,因此无法完全复制到frame。使用 sizeof 运算符查找大小。

char frame[sizeof(INFO)]; // Let compiler decide size of frame
INFO test1 = INFO();
test1.a='y';
test1.b=4000;
test1.c=9000;
strcpy(test1.g, "Goodbye World");
memcpy(frame, &test1, sizeof(INFO)); // copy memory and not string