问题
I am trying to dynamically store the contents of a pointer into a struct. I defined the struct as follows:
struct msg3 {
uint16_t msgSize; // 2 bytes
uint16_t msgType; // 2 bytes
uint32_t symbolIndex; // 4 bytes
};
I then proceed to initialize a struct of type msg3 using code below. (Packet is of type const u_char*).
const msg3* msg3_ = reinterpret_cast<const msg3*>(packet);
The above works fine, and sizeof(msg3) accurately returns 8.
Following the first 8 bytes in packet, there is 11 bytes of null-terminated ASCII characters.
I try to add a string as an element of the struct to capture the following 11 bytes of ASCII characters that are null-terminated:
struct msg3 {
uint16_t msgSize; // 2 bytes
uint16_t msgType; // 2 bytes
uint32_t symbolIndex; // 4 bytes
std::string symbol; // 11 bytes
};
Under this definition of struct (with the additional symbol element), sizeof(msg3) returns 32 when I want it to return 19. Plus, when I try to access msg3_.symbol, I get a segmentation fault. Why is this happening?
Essentially, I am trying to replicate
std::string symbol = (char*)packet + 8;
within the definition of the struct.
来源:https://stackoverflow.com/questions/62725064/initialize-string-type-elements-in-a-struct