[英]Setting the size of an array inside a struct with a value of another value within the same struct, in C
struct {
uint16 msg_length;
uint8 msg_type;
ProtocolVersion version;
uint16 cipher_spec_length;
uint16 session_id_length;
uint16 challenge_length;
V2CipherSpec cipher_specs[V2ClientHello.cipher_spec_length];
opaque session_id[V2ClientHello.session_id_length];
opaque challenge[V2ClientHello.challenge_length;
} V2ClientHello;
是否可以执行与上述类似的操作( http://tools.ietf.org/html/rfc5246 )? 如果是这样,我该如何在C中进行编码?
更具体地说,此行在struct中:
V2CipherSpec cipher_specs [V2ClientHello.cipher_spec_length];
用途:
V2ClientHello.cipher_spec_length
在相同的结构中定义,以设置数组的长度。
C不支持动态大小的数组。 为了实现您的目标,可以将V2CipherSpec
类型的指针用作结构变量,并在以后的阶段使用V2ClientHello.cipher_spec_length
值分配内存。
绝对不。 C没有动态大小的数组。 相反,我们可以依靠这样的技巧:
struct {
uint16 msg_length;
uint8 msg_type;
ProtocolVersion version;
uint16 cipher_spec_length;
uint16 session_id_length;
uint16 challenge_length;
char extra[0]; // or 1 if your compiler hates this
} V2ClientHello;
然后,不要直接创建此结构的实例,而是通过malloc():
struct V2ClientHello* hello = malloc(sizeof(V2ClientHello) +
len1*sizeof(V2CipherSpec) + len2 + len3);
现在,您已经具有所需大小的动态分配结构。 您可以使访问器函数获得“额外”字段:
V2CipherSpec* get_spec(V2ClientHello* hello, int idx) {
assert(idx < hello->cipher_spec_length);
return ((V2CipherSpec*)&hello->extra)[idx];
}
当然,您可以将malloc()调用包装在一个create例程中,该例程接受所有三个动态部分的大小,并在一个地方进行所有操作以增强鲁棒性。
RFC中显示的代码是伪代码,您不能如图所示实施它。
一旦知道它们的值,就需要根据V2ClientHello.cipher_spec_length
和其他长度指定字段手动分配这些数组。
值“ V2ClientHello.cipher_spec_length”在编译时不可用。 您不能在运行时指定数组的大小,而可以使用:
V2CipherSpec * cipher_specs;
在struct中使用malloc或calloc在运行时分配一块内存。
V2ClientHello.cipher_specs =(V2CipherSpec *)malloc(V2ClientHello.cipher_spec_length);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.