【问题标题】:converting struct to char* and back将 struct 转换为 char* 并返回
【发布时间】: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 是完全错误的。当它遇到零字节时,它将停止发送数据(bc 中有大量零字节)。最后,我对未使用的全局变量 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 的大量问题

标签: c++ struct char


【解决方案1】:

这段代码有一些问题,但导致问题的原因是使用sprintfbinary 数据从结构复制到字符数组:如果有 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*memcpy 接受void*
  • 为什么要复制 sizeof(frame)?那不应该是 sizeof(INFO) 吗?如果 OP 只是做了memcpy(&amp;test2, &amp;test1, sizeof(INFO));,那就更有意义了
  • @CantChooseUsernames,这将是缓冲区溢出,因为这里 frame 小于 INFO
  • 感谢 Joni 成功了!我知道其余的代码看起来很糟糕,但这是我快速拼凑起来的一个玩具程序,以询问我的真正问题。再次感谢!
【解决方案2】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-19
    • 2012-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多