I'm trying to create a data structure that contains something analogous to nested tables.
In my program I want to create a message structure that contains information about a message and then link to this message information on each field within the message. I was thinking of doing this using an array of structs within my message struct (see below). I also thought it would be better to have a pointer to the array of message fields as this means the array could be of variable length and declared constant elsewhere (saving resources).
I am however having issues with the syntax and accessing the subfields and was hoping someone could point out where I'm going wrong. As I understand it I've created a constant pointer to a constant message field structure within my message structure.
typedefstruct
{
int foo;
/*whatever needs to be in each field*/
}
message_field;
typedefstruct
{
uint32_t message_id;
size_t num_fields;
message_field fields[]; // the flexible array member must be last
}
message;
message *alloc_message(const size_t num_fields)
{
const size_t size = sizeof(message) + (num_fields * sizeof(message_field));
message *msg = (message*)malloc(size);
if (msg)
{
memset(msg, 0, size);
msg->num_fields = num_fields;
}
return msg;
}
void do_something_with_message(const message *const msg)
{
for (size_t i = 0; i < msg->num_fields; ++i)
{
printf("%d\n", msg->fields[i].foo);
}
}
int main()
{
message *msg = alloc_message(42);
if (msg)
{
msg->fields[7].foo = 13;
do_something_with_message(msg);
free(msg);
}
}
________
If you want to go with a more C++-like solution, consider converting message into a class and use an STL container, for example std::vector, as a member variable to store a variable number of the fields.
Here message_id, number_of fields etc are const but not initialised - so they will contain an unknown value which can't be changed!
Also if you have a const that contains a constant value that doesn't change (ie a const number) between instantiations then consider making them static.