将char数组转换为c中的structs数组

时间:2020-12-23 23:53:10

标签: c struct

我有一个 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.

我哪里出错了?

1 个答案:

答案 0 :(得分:1)

使用 pragma pack,它适用于大多数编译器

#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);
}
相关问题