Article From:

struct DATA {

    unsigned char nStart1;
    unsigned char nStart2[1];
    unsigned char nOrder;
    unsigned char nID;
    signed nT;
    signed int nTemp;
    int nCRC;
    unsigned char nEnd;

Would you like to assign the above data structure to char buff[]?
Can it be realized with memcpy?

Answer 0:

Of course, you can use memcopy.
At this level, you can give up data as a type of concept, that is, all the data is not type, that is a memory area, that is, a memory area is copied to another memory area.

However, if you want to use this method to communicate or save as a file, you have to pass it to other programs, and you have to pay attention to data format compatibility and byte order.

Answer 1:

1.It is sure that you can use memcpy to copy the memory content of the structure DATA variable into the buffer of the char array, but notice that the structure is required for memory alignment, so the structure variable may eventually have some fill bytes for memory alignment, and the contents of the fill are random.

2.If you operate this way, it is sure to send the information of the structure variable to other processes by network or pipe. This operation of the structure variable to byte stream is called the serialization process, the serialization process needs to consider the problem of the network byte order and local byte order, and of course, the process of the anti serialization.The byte stream needs to be converted into a structure after the byte stream is received. Currently, the popular serialization and anti serialization libraries have JSON and protobuf, which have a encapsulated serialization and anti serialization interface, making the whole serialization and anti serialization process transparent to the user.

3.The end of this problem is to implement the protocol encapsulation of the application layer data, and recommend… This article has a detailed description of the 1 and 2 points above.

Link of this Article: Structure assignment to array

Leave a Reply

Your email address will not be published. Required fields are marked *