title: Dynamically Populate Struct in C
body: <p>Say you have a struct in C:</p>
  <pre><code>typedef struct ID_Info {
    uint16_t model_number;
    uint16_t serial_number;
    uint16_t firmware_version;
  } ;
  ID_Info id_info;
  </code></pre>
  <p>Now, say I need to set each uint16 variable in this struct to the values of data received byte by byte. So for example, if I received the following bytes: 0x00, 0x11, 0x22, 0x33, 0x44 and 0x55 in some data array data[], I now need to set the values as follows:</p>
  <pre><code>id_info.model_number = data[1]*256 + data[0];     // 0x1100
  id_info.serial_number = data[3]*256 + data[2];    // 0x3322;
  id_info.firmware_version = data[5]*256 + data[4]; // 0x5544;
  </code></pre>
  <p>This is easy enough to hard code as shown above. However, I'd like to be able to do this without hard-coding values and iteratively if possible. Therefore, if I needed to add a variable to the struct, my code and loop would automatically know I need to iterate for two more bytes (assuming a unit16). So this loop would need to iterate foreach member in the struct. Furthermore, is there a way to infer the variable type to know how many bytes I need? Say I needed to add a uint8, and in this case the code could know I only need one byte.</p>
  <p>So maybe the pseudo-code would look something like this:</p>
  <pre><code>int i = 0;
  foreach(member in id_info)
    if(member is uint8)
      id_info.member = data[i];
      i =+ 1;
    else if (member is uint16)
      id_info.member = data[i] + 256*data[i+1];
      i =+ 2;
    else
      throw error
  </code></pre>
  <p>This way I could easily add and removed struct members without many changes to the code. Thanks in advance for any insight!</p>