在struct *中为char *数组分配空间

时间:2017-10-13 22:55:33

标签: arrays struct char

我正在尝试在结构中分配空间。该结构包含网络数据包的信息。

结构:

struct STRUCT_SVC_ROOM_CREATE
{
    PacketHeader Header;
    unsigned char TitleLength;
    char* RoomTitle = new char[TitleLength];
    short SuddenFactor;
    short GameModeFactor;
    unsigned char Password[4];

    int MaxMen;
};

请参阅这两行代码

unsigned char TitleLength;

char * RoomTitle = new char [TitleLength];

1st - >文字长度( 1 字节)

第二 - >文本本身( TitleLength 字节)

这就是我如何根据另一个创建结构。

STRUCT_SVC_ROOM_CREATE* RoomCreate = (STRUCT_SVC_ROOM_CREATE*)pHeader;

pHeader是另一个结构,它包含所有信息。然后我放入另一个结构来获得正确的数据位置。

但它不起作用。所以问题是:如何正确分配空间并使用 TitleLength 中指定的大小构建struct char *?

1 个答案:

答案 0 :(得分:0)

您不应该初始化结构定义中的对象。

struct STRUCT_SVC_ROOM_CREATE
{
    PacketHeader Header;
    unsigned char TitleLength;
    char* RoomTitle;
    short SuddenFactor;
    short GameModeFactor;
    unsigned char Password[4];

    int MaxMen;
};

void someFunction()
{
   STRUCT_SVC_ROOM_CREATE* foo = new STRUCT_SVC_ROOM_CREATE;
   foo->TitleLength = 10;
   foo->RoomTitle = new char[foo->TitleLength];

}

这是请求的类实现(未测试):

class SVC_ROOM_CREATE{

private:
    PacketHeader Header;
    char* RoomTitle;
    short SuddenFactor;
    short GameModeFactor;
    unsigned char Password[4];

    int MaxMen;

public:
    SVC_ROOM_CREATE(PacketHeader packet_header, int length, short sud_factor, short gm_factor, unsigned char pwd[], int max)
    {
        Header = packet_header;
        RoomTitle = new char[length];
        SuddenFactor = sud_factor;
        GameModeFactor = gm_factor;
        memcpy( Password, pwd, sizeof(Password));
        MaxMen = max;
    }


};

int _tmain(int argc, _TCHAR* argv[])
{
    PacketHeader Header;
    unsigned char bar[4] = "pas";
    int TitleLength = 10;
    int SuddenFactor = 1;
    int GameModeFactor = 2;
    int MaxMen = 15;
    SVC_ROOM_CREATE* foo = new SVC_ROOM_CREATE(Header, TitleLength, SuddenFactor, GameModeFactor, bar, MaxMen);

    return 0;
}