Reputation: 491
I am trying to create a function which can take any number of arguments of types char, char*, and int, after the first two arguments. But I am having trouble getting it to accept values other than char*. Here is what I have:
int formatter (char *str, const char *format, ...) {
va_list valist;
va_start(valist, format);
int i;
for (i = 0; i < strlen(format); i++) {
switch (format[i]) {
case '1':
strcat(str, va_arg(valist, char*));
}
}
va_end(valist);
return 1;
}
The call that is causing the program to crash:
int leet = 1337;
char temp[10] = "Hello!";
char result[100] = "";
formatter(result, "1 My name is 1", temp, leet);
Upvotes: 1
Views: 77
Reputation: 793
When using variadic arguments (in C), there is no direct way inside the function to know what arguments you are given. The usual workaround is that one of the parameter (in your case, like in many others, the format
parameter) is used to determine the types of the extra parameters.
Every time you call va_arg, you must tell what is the type of the next parameter. This is not only for typing, but also because the size of the parameter is required to update the "behind the scenes" pointers.
If you modifiy your loop that way:
switch (format[i]) {
case '1':
doSomethingWithAString(va_arg(valist, char*));
break;
case '2':
doSomethingWithAInt(va_arg(valist, int));
break;
}
Then when you call your function, you'll be able to use the format parameter to say which parameters are a string, and which ones are a int. For example:
formatter(str, "12221", str1, i1, i2, i3, str2);
With your example, you are passing a integer when your format string tells the formatter is supposed to expect a string. Hence a crash.
Upvotes: 5