I’m having a problem with my variadic function print_all
when I compile and test the code below:
int main(void)
{
print_all("ceis", 'B', 3, "stSchool");
return (0);
}
It prints B, 66
instead of B, 3, stSchool
.
I expect the problem is with va_arg
in each function, but due to my limited knowledge of variadic functions, I’m unable to make changes. I also don’t want to implement it with a switch
statement to modularize my program.
The problem is indeed with the usage of va_arg
in the print_all
function. The issue is that va_arg
requires you to specify the type of the argument you are trying to retrieve. In your code, you are assuming that all arguments are of type int
, which is not correct.
To fix the issue, you need to modify the print_all
function to handle different types of arguments correctly. One way to do this is to use the format string to determine the type of each argument.
Here’s an updated version of the print_all
function that should work correctly:
#include <stdarg.h>
#include <stdio.h>
void print_all(const char* format, ...)
{
va_list args;
va_start(args, format);
for (int i = 0; format[i] != '\0'; i++)
{
switch (format[i])
{
case 'i':
printf("%d", va_arg(args, int));
break;
case 'c':
printf("%c", va_arg(args, int));
break;
case 's':
printf("%s", va_arg(args, char*));
break;
default:
// Ignore unrecognized format characters
break;
}
// Print comma after each argument except the last one
if (format[i + 1] != '\0')
{
printf(", ");
}
}
va_end(args);
}
int main(void)
{
print_all("ceis", 'B', 3, "stSchool");
return 0;
}
This updated print_all
function uses a switch
statement to handle different format characters (i
, c
, s
) and retrieve the corresponding arguments using the correct type. It also prints a comma after each argument except the last one.
When you run the code now, it should print B, 3, stSchool
as expected.