Home > Blockchain >  Copy data to struct in a serial way in C
Copy data to struct in a serial way in C

Time:10-30

I have a packed struct like this one below

struct MyStruct
{
    uint8_t a;
    uint32_t b;
    uint16_t c;
    uint8_t d[4];
    uint16_t e[2];
    uint32_t crc_field;
} __attribute__((packed));

I want to store data to it in a serial way, meaning that I want to use memcpy or for loop to copy data from an array into this struct above.

Consider the example:

uint8_t Buffer[64]; //We assume it contains some data.
MyStruct foo; 
memcpy(&foo, Buffer, sizeof(MyStruct));

Assuming that I always check the crc_field and the data into the Buffer was stored in the opposite way (from another MyStruct earlier, to Buffer). Would there be any issue with this approach?

Would it be better to use a union instead?

union MyUnion
{
    uint8_t raw_data[19];
    struct MyStruct
    {
        uint8_t a;
        uint32_t b;
        uint16_t c;
        uint8_t d[4];
        uint16_t e[2];
        uint32_t crc_field;
    } __attribute__((packed));
}

uint8_t Buffer[64]; //We assume it contains some data.
MyUnion foo; 
memcpy(foo.raw_data, Buffer, sizeof(MyStruct));

CodePudding user response:

The MyStruct class is trivially copyable. It means that you can safely copy its byte representation in a buffer, and when you will copy back that representation into a MyStruct object, that object will take the original value. No need for an union here.

Simply, as the representation of scalar type is not defined in the standard, using that to exchange data between different systems or application compiled with different options could invoke Undefined Behaviour. It may not be a concern, if your compiler documents the standard type and struct representations (probable as you are using the non standard __attribute__((packed))). Simply it is restricted to one environment and is no longer a portable C program...

  • Related