Hello!
Recently I've been working on a project which requires an API, the user supplies a function pointer which returns a specific value, this function needs a list of string arguments, similar to what you may find in the "main" function. I first thought maybe some sort of linked list but that would be inefficient so I decided on this. I first didn't really know how to implement it but after some fiddling I managed to implement this procedure to return a char**
with the specified strings.
#include <stdarg.h>
char **new_argv(int count, ...)
{
va_list args;
int i;
char **argv = malloc((count+1) * sizeof(char*));
char *temp;
va_start(args, count);
for (i = 0; i < count; i++) {
temp = va_arg(args, char*);
argv[i] = malloc(sizeof(temp));
argv[i] = temp;
}
argv[i] = NULL;
va_end(args);
return argv;
}
It is a variadic function (can accept a variable amount of arguments, ...
) it accepts the amount of strings given, and the strings.
Example use:
void example()
{
char **argv = new_argv(4, "This", "is", "a", "test");
// argv[0] == "This"
// argv[2] == "a"
}
I'm mainly posting this for two reasons, for people to test it and give feedback, mainly about memory efficiency, and to demonstrate it if other people need something similar in their projects.
Thanks for reading!