【问题标题】:Convert char array to structs array in c在c中将char数组转换为structs数组
【发布时间】:2020-12-23 23:53:10
【问题描述】:

我有一个 unsigned char*(从服务器发送的字节),我需要将它转换/转换为一个结构数组,其大小与 unsigned char* 的大小完全匹配。 不复制值,我该如何实现?在 uchar* 中,可以有任意数量的结构。

我如何做到这一点?

我尝试了以下(伪代码):

// Define the struct:
struct MyStruct:
    unsigned char name[6]
    long time
    double speed

// ...some code...

// Get the uchar*.
unsigned char* chars = getUchars()

// The uchar*'s first byte is a special flag,
// so the structs start at index 1 not 0.
unsigned char* chars2 = &chars[1]

// Convert chars2 to an array of MyStructs.
MyStruct *structs = (MyStruct*) chars2

// Get the first struct and print values.
MyStruct s1 = structs[0]
_print(charArrayToString(s1.name), s1.time, s1.speed)
// When this _print() is called, the struct's
// name value is printed correctly, but its time
// and speed are not printed correctly.

// Get the second struct.
MyStruct s2 = structs[1]
_print(charArrayToString(s2.name), s2.time, s2.speed)
// None of this second struct's name, time and speed
// is printed correctly.

我在哪里犯错了?

【问题讨论】:

  • long 和 double 有对齐要求。 chars2 可能没有正确对齐。
  • 您可以通过使用特定于实现的选项来制作打包结构来解决它。
  • 在你的结构上创建一个 dump() 函数,它可以逐字节转储它,也可以按数据成员转储。您可能会发现那里有一些填充会导致问题。
  • 感谢您的回复。逐字节和按数据成员转储它是什么意思?您的意思是单独设置每个结构的名称、时间和速度,而不是将整个 uchar2 直接转换为 MyStruct*?

标签: c struct


【解决方案1】:

使用编译指示包,它适用于大多数编译器

#include <stdio.h>

struct DefaultPack
{
    char str[6];
    long time;
    double speed;
};

#pragma pack(push,1)
struct Packed
{
    char str[6];
    long time;
    double speed;
};
#pragma pack(pop)


int main (int argc, char *argv[])
{
    struct DefaultPack n;
    struct Packed p;
    printf("Sizes of struct:\n"
           "Default packing: %lu\n"
           "Packed: %lu\n"
           "in packed struct:\n"
           "offset of time: %lu\n"
           "offset of speed: %lu\n"
           "in default packed struct:\n"
           "offset of time: %lu\n"
           "offset of speed: %lu\n",
           sizeof(struct DefaultPack),
           sizeof(struct Packed),
           (void*)&p.time  - (void*)&p.str[0],
           (void*)&p.speed - (void*)&p.str[0],
           (void*)&n.time  - (void*)&n.str[0],
           (void*)&n.speed - (void*)&n.str[0]
           );
    return(0);
}

【讨论】:

  • ----- 输出:结构的大小:默认打包:24 打包:打包结构中的 22:时间偏移量:6 速度偏移量:默认打包结构中的 14:时间偏移量: 8 偏移速度:16
猜你喜欢
  • 2011-06-08
  • 2016-04-07
  • 2012-04-29
  • 1970-01-01
  • 2014-03-02
  • 1970-01-01
  • 1970-01-01
  • 2013-05-02
  • 1970-01-01
相关资源
最近更新 更多