I want a function that, when called with a varying number of arguments, return the first non-NULL one. I’ve tried this, but it core dumps on for loop:
char *first(char *args, ...)
{
va_list ap;
char *r = NULL, *p;
va_start(ap, args);
for (p = args; *p; p++) {
r = va_arg(ap, char*);
if (r != NULL) break;
}
va_end(ap);
return r;
}
char *q = NULL;
char *w = NULL;
char *e = "zzz";
char *r = NULL;
printf("%s\n", first(q, w, e, r)); // ought to print "zzz"
argsis not an array of arguments. It’s just the first argument you passed tofirst. So its value in this case is the value ofq.You can’t iterate over va args like you are doing.
Do this:
This will crash if you have no non-NULL argument, though, so you would better pass the number of arguments as first argument:
Alternatively, use a sentinel: