换个花样玩C++(2)柔性数组怎么玩
如果你涉足网络传输方向的开发,我想你对这段类似的代码应该不会很陌生,先看代码:
int check_msg(svr_proto_t* pkg, uint32_t bodylen, fdsession_t* fdsess)
{struct report_msg {uint32_t gameid;uint32_t userid;uint32_t recvid;uint32_t onlineid;uint32_t maptype;uint32_t mapid;uint32_t timestamp;uint32_t msglen;char msg[]; }__attribute__((packed));if (bodylen <= sizeof(report_msg)) {KERROR_LOG(pkg->id, "invalid len\t[%u]", bodylen);return 0;}report_msg* pmsg = (report_msg *)pkg->body;if (pmsg->msglen + sizeof(report_msg) != bodylen) {KERROR_LOG(pkg->id, "invalid len\t[%u %u]", bodylen, pmsg->msglen);return 0;} //TODO other logicreturn 0;
}
这里你会看到有report_msg 这个结构体,他的msg成员是一个数组,数组长度是0,当然你也可以写成 char msg[0];到这里就引出数组的另外一种玩法---柔性数组。
柔性数组
在c99中有明确的规定允许结构体中最后一个数组大小是未知的。
柔性数组其实是结构体中的最后一个数组未说明大小,且结构体中至少包含一个以上其