Fullaccess
Fullaccess

Reputation: 161

Is there a way to take the variable arguments of main() and use them in my own function?

I'm a student learning how to code in c, so I have basically no idea what I'm doing but anyway here's my code. Even though I have the number of arguments once I run the code, I cant use them in my function without implementing some kind of argument limit.

int main(int argc, char const *argv[])
{
    max(argc -1, /* help please */)
    return 0;
}

int max(int count, ...)
{
    int max = INT_MIN;
    int current = 0;

    va_list arg;
    va_start(arg, count);
    for (int i = 0; i < count; i++)
    {
        current = va_arg(arg, int);
        if (max < current)
        {
            max = current;
        }
    }
    va_end(arg);
    return max;
}

Upvotes: 1

Views: 69

Answers (3)

ikegami
ikegami

Reputation: 386386

You would need

if      (argc == 1) { max(argc-1); }
else if (argc == 2) { max(argc-1, argv[1]); }
else if (argc == 3) { max(argc-1, argv[1], argv[2]); }
else if (argc == 3) { max(argc-1, argv[1], argv[2], argv[3]); }
// etc

This is no good. Instead, accept an "array".

// n must be at least 1.
int max(int n, const int *nums) {
    int max = nums[0]
    while (n--) {
       if (nums[i] > max)
          max = nums[i];
    }

    return max;
}


int main(int argc, char const *argv[]) {
    int n = argc - 1;
    if (!n) {
       fprintf(stderr, "usage\n");
       exit(1);
    }

    int *nums = malloc(n);
    if (!nums) {
       perror("malloc");
       exit(1);
    }

    for (int i=0; i<n; ++i) {
       nums[i] = atoi(argv[i+1]);
    }
  
    printf("%d\n", max(n, nums));

    free(nums);
    return 0;
}

It makes no sense for max to convert the strings to numbers, so I fixed that.

Upvotes: -1

anatolyg
anatolyg

Reputation: 28278

The standard way of passing several arguments of the same type is by using an array, just like main itself does. Variable arguments (va_arg) are for arguments of different types; it's harder to use.

You probably want to cut off the first element (the name of the program itself). Here is how to do it:

int main(int argc, char const *argv[])
{
    max(argc - 1, argv + 1);
    return 0;
}

int max(int count, char const *arguments[])
{
    ...
}

Note: the arguments of int max(...) are still strings. You should convert them to integers inside the function, one by one.

Upvotes: 1

dbush
dbush

Reputation: 224387

You don't need variable arguments here. Just pass argc and argv directly to your function and loop through the arguments:

int max(int argc, char const *argv[])
{
    int max = INT_MIN;
    int current = 0;

    int i;
    for (i=1;i<argc;i++) {
        current = atoi(argv[i]);
        if (max < current)
        {
            max = current;
        }
    }
    return max;
}

int main(int argc, char const *argv[])
{
    max(argc, argv);
    return 0;
}

Upvotes: 1

Related Questions