将struct转换为char *并返回

时间:2013-10-05 18:55:15

标签: c++ struct char

我正在尝试将我的结构转换为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;
  }

输出:

y
-858993460
-858993460
╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠

只有test2.a是正确的。我将它转换为char *错误,还是我将其转换回来的方式?感谢

2 个答案:

答案 0 :(得分:6)

此代码存在一些问题,但导致问题的是使用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));

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

答案 1 :(得分:3)

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
相关问题