Search code examples
c++data-structurespackets

Method for making a variable size struct


I need to craft a packet that has a header, a trailer, and a variable length payload field. So far I have been using a vector for the payload so my struct is set up like this:

struct a_struct{
 hdr a_hdr;
 vector<unsigned int> a_vector;
 tr a_tr;
};

When I try to access members of the vector I get a seg fault and a sizeof of an entire structs give me 32 (after I've added about 100 elements to the vector.

Is this a good approach? What is better?

I found this post Variable Sized Struct C++ He was using a char array, and I'm using a vector though.


Solution

  • The solution in the other SO answer is c-specific, and relies on the peculiarities of c arrays - and even in c, sizeof() won't help you find the "true" size of a variable size struct. Essentially, it's cheating, and it's a kind of cheating that isn't necessary in C++.

    What you are doing is fine. To avoid seg faults, access the vector as you would any other vector in C++:

    a_struct a;
    for(int i = 0; i < 100; ++i) a.a_vector.push_back(i);
    cout << a.a_vector[22] << endl; // Prints 22