Initialize string type elements in a struct

人盡茶涼 提交于 2020-07-23 06:22:17

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!