Randomer
Randomer

Reputation: 31

How to correctly use va_list,add,start,end?

I am working my way to creating my own printf function. I am starting with smaller functions that will be required to finish the main project.

My function should return the sum of the arguments if i = 0, or it should return the sum of the size of the last nb character strings passed as parameter if i = 1. So if I have: ./a.out 0 2 3 3 , it should return 6, for example. However, all I get is 1, and if the second argument is 3, then I get a weird negative number.

Can someone help me figure this out or at least point me in the right direction? Thank you in advance!

I tried using vprintf but I don't know how to properly use it. By the way, the only reason I am using printf right now is for testing. I will make Unit Tests after I'm done.

#include <stdio.h>
#include <stdarg.h>
#include <string.h>

int my_getnbr(char const *str);

int sum_stdarg(int i, int nb, ... )
{
    int j = 0;
    int signal = 0;
    va_list(args);

    va_start(args, nb);
    while (nb > j) {
        if(i == 0) {
        signal = signal + va_arg(args, int);
    }
        else if (i == 1) {
        signal = signal + strlen(va_arg(args, char*));
    }
    j++;
    }
    va_end(args);
    return (signal);
}

int my_getnbr(char const *str)
{
    int i = 0;
    long cpy = 0;
    int intcpy;

    while ((str[i] < '0' || str[i] > '9') && str[i] != '\0')
        i++;
    if (str[i - 1] == '-') {
        while ((str[i] >= '0' && str[i] <= '9') && str[i] != '\0') {
            cpy = cpy * 10 - (str[i] - 48);
            i++;
        }
    } else {
        while ((str[i] >= '0' && str[i] <= '9') && str[i] != '\0') {
            cpy = cpy * 10 + (str[i] - 48);
            i++;
        }
    }
    if (cpy < -2147483648 || cpy > 2147483647)
        return (0);
    intcpy = cpy;
    return (intcpy);
}

int main(int ac, char **av)
{
    printf("%d\n", sum_stdarg(my_getnbr(av[1]), my_getnbr(av[2])));
    return (0);
}

Upvotes: 0

Views: 759

Answers (1)

l.k
l.k

Reputation: 199

va_list(args);

va_list is a type, not a function. You're supposed to declare a variable of type va_list and for use with the other va_* things.

Next up:

int sum_stdarg(int i, int nb,  ... )  // '...' declared as third parameter
[...]
printf("%d\n", sum_stdarg( my_getnbr(av[1]),   my_getnbr(av[2])));  // 'sum_stdarg' called with 2 arguments

You haven't actually supplied any of the arguments va_start is supposed to access. Calling va_start here will cause undefined behaviour.

If your second arg is 3, then when you call sum_stdarg, neither if in the while loop ever fires, so your return variable is never assigned to and still contains uninitialized memory when you return.

Upvotes: 1

Related Questions