0

I have a structure which members are char arrays of multiple sizes:

typedef struct data_hex_t
{
    char bat[12];
    char cell_1[5];
    char cell_2[4];
    char cell_3[4];
    char cell_4[4];
} data_hex_t;

I want to iterate over them to find its size with sizeof (or something similar) like this:

data_hex_t data_hex;

size_t last_member_size = 0;
for(size_t i = 0; i < sizeof(data_hex); i += last_member_size)
{
    member_size = sizeof(ITERATOR_OF_ARRAY_WITHIN_STRUCT + i);
    last_member_size = member_size;
}

Is that even possible to do in C?

  • You can iterate over arrays, but not over structure members. See e.g. [Why isn't sizeof for a struct equal to the sum of sizeof of each member?](https://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member?rq=1) for one reason. – Some programmer dude May 22 '21 at 14:17
  • It is time to rethink your data model. – Cheatah May 22 '21 at 14:19
  • 3
    And *why* do you want to iterate over the structure members? What is the underlying problem that is supposed to solve? – Some programmer dude May 22 '21 at 14:19
  • 1
    This is a solution for a embedded device, I will be receiving data via UART communication, and get an array of hexadecimal values. Some sets of those values have a meaning, e.g. the first 12 hexadecimal values are general info about the battery, then the following 5 values are about a cell and goes on like that. I want to automatically go through the entire string and store those in individual variables over a structure. – Erick Castillo May 22 '21 at 14:26
  • That's not really possible the way you want it. But you can just do e.g. `memcpy(data_hex.bat, source_data, 12); memcpy(data_hex.cell_1, source_data + 12, 5);` etc. – Some programmer dude May 22 '21 at 14:30
  • Yeah, that's how I'm doing it right now, I was looking for a way to automate it, but as you say is not possible. Thank you! – Erick Castillo May 22 '21 at 14:35
  • You can do this `char* data_hex_char = (char*)data_hex;` and iterate over `data_hex_char` as if it were one big array overlapping with the struct (note, the type must be `char*` or a signedness variant). No need to copy. Note also that your data structure could in theory have holes, but since this data is mapped onto some externally fixed wire format, you should know where these holes, if any, are. – n. m. could be an AI May 22 '21 at 15:11
  • have you tried using `offsetof` ? – tstanisl May 22 '21 at 20:19

0 Answers0