title: Resize array of structs within a function
body: <p>I want to dynamically add new elements to a array of structs. I have added a minimal example that segfaults. I think I have to pass a pointer <code>struct data **arr</code> to the function to reallocate and add new element correctly, but I haven't been able to do it correctly.</p>
  
  <pre><code>#include &lt;string.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  
  struct data {
      char s[10];
      int arr[10];
  };
  
  void add_one_element(struct data *arr, int *num_elements)
  {
    /*increment counter*/
    *num_elements +=1;
    arr = realloc(arr, *num_elements * sizeof(struct data));
  
    strcpy(arr[*num_elements-1].s, "ABC");
    for(int i = 0; i &lt; 10; i++)
      arr[*num_elements-1].arr[i] = i;
  }
  
  
  int main()
  {
     struct data *arr = NULL;
     int num_elements = 0;
     add_one_element(arr, &amp;num_elements);
  
     printf("arr.s = %s\n", arr[num_elements-1].s);
     for(int i = 0; i &lt; 10; i++)
          printf("arr[%d].arr[%d] = %d\n", num_elements-1, i, arr[num_elements-1].arr[i]);
  
     free(arr);
     return 0;
  }
  </code></pre>
  
  <p>EDIT 1: Tried to correct the problem. This time I get <code>test(91537,0x7fff79532000) malloc: *** error for object 0x7fff5f5c0ad0: pointer being realloc'd was not allocated</code>. Which suggest that the reallocation failed.</p>
  
  <pre><code>#include &lt;string.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  
  struct data {
      char s[10];
      int arr[10];
  };
  
  void add_one_element(struct data **arr, int *num_elements)
  {
    /*increment counter*/
    *num_elements +=1;
    arr = realloc(arr, *num_elements * sizeof(struct data));
  
    strcpy(arr[*num_elements-1]-&gt;s, "ABC");
    for(int i = 0; i &lt; 10; i++)
      arr[*num_elements]-&gt;arr[i] = i;
  }
  
  
  int main()
  {
     struct data *arr = NULL;
     int num_elements = 0;
     add_one_element(&amp;arr, &amp;num_elements);
     printf("arr.s =&gt; %s\n", arr[num_elements-1].s);
     for(int i = 0; i &lt; 10; i++)
          printf("arr[%d].arr[%d] = %d\n", num_elements-1, i, arr[num_elements-1].arr[i]);
     return 0;
  }
  </code></pre>