I was thinking that it would be nice to somehow have one function to initialize all the options and to regroup them in one structure (like the one I posted above).
Since I never played around with variable parameter lists yet, I read up on it and came up with this little code:
Code:
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
typedef struct {
char **values;
int size;
} options;
options initOptions(int, ...);
void printOptions(options*);
main()
{
options myOptions = initOptions(2, "test", "test2");
options myOptions2 = initOptions(3, "test", "test2", "test3");
printOptions(&myOptions);
printOptions(&myOptions2);
return 0;
}
void printOptions(options* myOptions)
{
int i;
for (i = 0; i < myOptions->size; i++)
printf("%s\n", myOptions->values[i]);
}
options initOptions(int n, ...)
{
options myOptions;
int i;
va_list ap;
char *tmp;
myOptions.size = n;
myOptions.values = malloc(n * sizeof(char *));
va_start(ap, n);
for(i = 0; i < n; i++) {
tmp = va_arg(ap, char *);
myOptions.values[i] = malloc((strlen(tmp)+1) * sizeof(char));
strcpy(myOptions.values[i], tmp);
}
va_end(ap);
return myOptions;
}