title: Structures with dynamic memory allocation in C
body: <p>I need to write data into a structure where the length of the data depends on the command I want to send to a device. For that I have defined the following structure:</p>
  
  <pre><code>typedef struct {
      uint8 len;          // Command length (cmd ... crc)
      uint8 cmd;          // Command code
      uint8 data_length;  // Data length
      uint8 data[12];     // Data: max 12 Byte
      uint8 crc_h;        // CRC value MSB
      uint8 crc_l;        // CRC value LSB
  }CMD_TYPE;
  </code></pre>
  
  <p><strong>Note:</strong> the members <em>cmd</em>, *data_length* and <em>crc</em> that are always present, instead member <em>data</em> can be empty or contains up to 12 Bytes.</p>
  
  <p>I have created a function that returns a initialized command according to the parameters passed to the function:</p>
  
  <pre><code>CMD_TYPE Device::get_cmd(uint8 cmd, uint8 data_len, uint8 *data)
  {
      CMD_TYPE cmd;
  
      cmd.len = (4 + data_len) * sizeof(uint8);
      cmd.cmd = cmd;
      cmd.data_length = data_len;
      cmd.data = (uint8 *)realloc(cmd.data, data_len*sizeof(uint8));
      if(data_len &gt; 0)    memcpy(cmd.data, data, data_len);
  
      add_crc16((uint8*)&amp;cmd);
  
      return cmd;
  }
  </code></pre>
  
  <p>The function get_cmd() is used like this:</p>
  
  <pre><code>uint8 cmd_code = 0x01;
  uint8 data[2] = {0xAB, 0xCD};
  
  CMD_TYPE cmd = local_device-&gt;get_cmd(cmd_code, 2, data);
  retVal = local_device-&gt;send(cmd);
  </code></pre>
  
  <p>When I try to compile this code I get an error from the compiler for that line:</p>
  
  <pre><code>cmd.data = (uint8 *)realloc(cmd.data, data_len*sizeof(uint8));
  </code></pre>
  
  <p>and the compiler error is:</p>
  
  <pre><code>error: lvalue required as left operand of assignment
  </code></pre>
  
  <p>The aim of using <em>realloc()</em> is to re-size the array data or to remove it at all from my new command structure. What is wrong in my code? Is that the right way to initialize structures with dynamic memory allocation?</p>