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.
In C# I can invoke a variadic function with an array, like this:
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")
}
}
}
In C I've got this:
#include <stdio.h>
#include <malloc.h>
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;
}
How can I do this in C?
(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?)
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
char *formatString = "My Formatted String %s.%s.%s";
char *formatValues[] = {"a","b","c","d","e"};
But I'll never have too few %s.
Note: the C has to work on GCC for Linux, and Visual Studio for Windows (C90).