title: How to correctly allocate memory to a dynamic array of integers stored in a struct?
body: <p>I have a function that sets values to a struct:</p>
  
  <p>My struct:</p>
  
  <pre><code>struct entry {
      char key[MAX_KEY];
      int* values;
      size_t length;
      entry* next;
      entry* prev;
  };
  </code></pre>
  
  <p>My function:</p>
  
  <pre><code>// Sets entry values
  void command_set(char **commands, int arg_num) {
      struct entry e;
      e.length++;
      strcpy(e.key, commands[1]);
      for (int i = 2; i &lt; arg_num; i++) {
          e.values[i - 2] = atoi(commands[i]);
      }
  }
  </code></pre>
  
  <p>where:</p>
  
  <ul>
  <li>**commands: is a array of strings</li>
  <li>arg_num: is how many strings are in the array</li>
  <li>key: is the name of the entry</li>
  <li>values: are integer values store in the entry</li>
  </ul>
  
  <p>I run the code and I get a segmentation fault 11. I have narrowed it down to the line:</p>
  
  <pre><code>e.values[i -2] = atoi(commands[i]);
  </code></pre>
  
  <p>I assume that I have to use malloc to allocate memory as I don't appear to have gone out of bounds with my loop. I have tried to understand the correct way to allocate memory however I can't seem to get the syntax correct for allocating sizeof(int) to a dynamic array of integers.</p>
  
  <p>I have tried:</p>
  
  <pre><code>e.values[i - 2] = malloc(sizeof(int));
  </code></pre>
  
  <p>and</p>
  
  <pre><code>e.values[i - 2] = (int) malloc(sizeof(int));
  </code></pre>
  
  <p>and</p>
  
  <pre><code>e.values[i - 2] = malloc(sizeof(int *));
  </code></pre>
  
  <p>However I get the error:</p>
  
  <pre><code>incompatible pointer to integer conversion assigning
    to 'int' from 'void *' [-Werror,-Wint-conversion]
  </code></pre>