title: How to use a variadic argument for its own data structure?
body: <p>To facilitate the use of a data structure that contains a string to be filled from a function, I would like to be able to define the same function with variadic arguments, like this:</p>
  
  <pre><code>struct my_struct_t
  {
      char *msg;
  };
  
  struct my_struct_t *fill(const char *fmt, ...);
  
  struct my_struct_t *filled = fill("A number: %d, a string: '%s'.", 43, "hello");
  </code></pre>
  
  <p>To do so, I implemented the following function, as well as variants, but the result was always wrong when I retrieved the string in the structure. Here is the code:</p>
  
  <pre><code>#include &lt;stdarg.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  struct my_struct_t
  {
      char *msg;
  };
  
  struct my_struct_t *fill(const char *fmt, ...)
  {
      va_list ap1, ap2;
      va_copy(ap2, ap1);
      va_start(ap1, fmt);
  
      int slen = snprintf(NULL, 0, fmt, ap1);
      va_end(ap1);
  
      char *str = malloc(slen);
      assert(str != NULL);
  
      va_start(ap2, fmt);
      snprintf(str, slen, fmt, ap2);
      va_end(ap2);
  
      struct my_struct_t *my_struct = malloc(sizeof *my_struct);
      assert(my_struct != NULL);
  
      my_struct-&gt;msg = str;
  
      return my_struct;
  }
  
  int main()
  {
      struct my_struct_t *filled = fill("A number: %d, a string: '%s'.", 43, "hello");
      printf("%s\n", my_struct-&gt;msg);
      return 0;
  }
  </code></pre>
  
  <p>This leads to different results with each execution, for example:</p>
  
  <blockquote>
    <p>A number: 7011816, a string: 'ðe'</p>
  </blockquote>
  
  <p>I guess this is a problem with the use of variadic arguments, however I haven't found how to solve my problem, i.e. save the string in the structure field with the formatting sent, so I'll expect this:</p>
  
  <blockquote>
    <p>A number: 43, a string: 'hello'.</p>
  </blockquote>