Is it able to define a variable length struct in gnuc to represent a object as follow:
field1: fixed 4bytes;
field2: length of field3
field3: variable length
field4: length of field5
field5: variable length
field6: fixed 8bytes
field7: fixed 1byte
I know in gnuc we can use the zero-size array to implement a variable length struct, e.g.
typedef struct varStruct{
int foo1;
int foo2[0];
}varStruct;
But the above usage requires the variable length field placed at the tail of the struct. What if they are in the middle?
You can't have a struct with more than one variable array or a variable array in the middle. Think about it, how would the compiler know where
field3
andfield4
start if the lengthfield2
is variable?If
field1
contains the length of the next two fields, you could read the members of the struct manually. Example code (read it as pseudocode):You'll need to do this with 3 structs and do a little address arithmetic at run-time:
Not possible, since the compiler (is responsible for and) will not be able to calculate offsets for
field4
andfield5
.