title: How do I format a string from an array of values in C?
body: <p>I've been using C# for the last few years, and right now I'm trying to write some C. I'm trying to format a string from an array of values. The "format string" and the array aren't known until runtime.</p>
  
  <p>In C# I can invoke a variadic function with an array, like this:</p>
  
  <pre><code>using System;
  
  namespace ConsoleApplication7
  {
      class Program
      {
          static void Main(string[] args)
          {
              string formatString = "{0}.{1}.{2}.{3}";
              string[] formatValues = new[] { "a", "b", "c", "d" };
  
              string formatted = String.Format(formatString, formatValues);
  
              //Do something with formatted (now looks like "a.b.c.d")
          }
      }
  }
  </code></pre>
  
  <p>In C I've got this:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;malloc.h&gt;
  
      int main(int argc, char* argv[])
      {
          char *formatString = "%s.%s.%s.%s";
          char *formatValues[] = {"a","b","c","d"};
  
          char *buffer = (char*)malloc(100 * sizeof(char));
  
          //This doesn't work.....
          sprintf(buffer, formatString, formatValues);
  
          //... buffer is junk
  
          return 0;
      }
  </code></pre>
  
  <p>How can I do this in C?</p>
  
  <p>(Is there a nice function in the C standard library I can use to help me, or perhaps, is there a way to call a varargs function with an array?)</p>
  
  <p>Please note, the number of arguments will never be greater than the length of the array I have. And the types will always be strings. So I might have</p>
  
  <pre><code>char *formatString = "My Formatted String %s.%s.%s";
  char *formatValues[] = {"a","b","c","d","e"};
  </code></pre>
  
  <p>But I'll never have too few %s.</p>
  
  <p>Note: the C has to work on GCC for Linux, and Visual Studio for Windows (C90).</p>