Erik W
Erik W

Reputation: 2628

C Variadic Function not working as intended

I'm trying to make a function that takes a string with format (like printf, but instead of "%i" I want it to be "n" (for learning purposes, don't ask me why)). Here is the function:

void test(char* args, ...)
{
    int length = strlen(args);
    va_list list;
    va_start(list, length);

    for (int i = 0; i < length; i++)
    {
        if (args[i] == 'n')
        {
            printf("%i", va_arg(list, int));
        }
    }
}

The problem is that when I call it like this: test("n", 13); it gives another number (-858993460). What's the problem and how can I fix it?

Upvotes: 0

Views: 288

Answers (1)

JuniorCompressor
JuniorCompressor

Reputation: 20015

You should call va_start like this:

va_start(list, args);

The second parameter of va_start must be the name of the last parameter of test before the ellipsis, which is args.

Upvotes: 3

Related Questions