C++ 将 struct 转换为 char* 并返回

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19201488/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:36:02  来源:igfitidea点击:

converting struct to char* and back

c++structchar

提问by rex

I am trying to convert my struct into a char*, and then back to a struct. But I guess I am missing something. Once it is returned to struct, only one attribute of the struct is correct. The rest is all wrong. Here is my code.

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

Output:

输出:

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

Only test2.a is correct. Am I converting it to a char* wrong, or is it the way I convert it back? Thanks

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

回答by Joni

There are a few problems with this code, but the one that's causing the problem is the use of sprintfto copy binarydata from the struct to the character array: if there's a NUL byte anywhere in the struct's data the copy will stop short. In this case there's a NUL char in the struct data right after the first member, either embedded in the second member or because of padding, so only the first member is copied entirely.

这段代码有一些问题,但导致问题的一个原因是使用sprintf二进制数据从结构复制到字符数组:如果结构数据中的任何地方都有 NUL 字节,则复制将停止。在这种情况下,结构数据中第一个成员之后有一个 NUL 字符,要么嵌入在第二个成员中,要么因为填充,所以只有第一个成员被完全复制。

Use memcpyinstead of sprintf.

使用memcpy代替sprintf

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

INFO test2 = INFO();
memcpy(&test2, frame, sizeof(frame));

Another problem is that the size of the INFO structure is likely not 128 because of padding and alignment, so it cannot be copied entirely to frame. Use the sizeofoperator to find the size.

另一个问题是 INFO 结构体的大小可能不是 128,因为填充和对齐,所以不能完全复制到frame. 使用sizeof运算符查找大小。

回答by Iuri Covalisin

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