How to convert struct to char array in C

前端 未结 10 527
孤城傲影
孤城傲影 2020-12-19 03:00

I\'m trying to convert a struct to a char array to send over the network. However, I get some weird output from the char array when I do.

#include 

        
10条回答
  •  梦毁少年i
    2020-12-19 03:31

    The signedness of char array is not the root of the problem! (It is -a- problem, but not the only problem.)

    Alignment! That's the key word here. That's why you should NEVER try to treat structs like raw memory. Compliers (and various optimization flags), operating systems, and phases of the moon all do strange and exciting things to the actual location in memory of "adjacent" fields in a structure. For example, if you have a struct with a char followed by an int, the whole struct will be EIGHT bytes in memory -- the char, 3 blank, useless bytes, and then 4 bytes for the int. The machine likes to do things like this so structs can fit cleanly on pages of memory, and such like.

    Take an introductory course to machine architecture at your local college. Meanwhile, serialize properly. Never treat structs like char arrays.

提交回复
热议问题