Error returning lower value

Asked

Viewed 98 times

0

I’m trying to return the lowest value using the va_args, which supports several arguments, but it always returns the same number: -13227;

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

int minimo(int args, ...) 
{
    int elemento, min;

    va_list valist;
    va_start(valist, args);

    min = INT_MAX;
    for(int i=0; i<args; i++)
    {
        elemento = va_arg(valist, int);
        if(elemento < min)
            min = elemento;
    }

    va_end(valist);

     return min;
}

int main() 
{           
    int num = minimo(8, 5, 3, 7, 12, 6);
    printf("%d\n", num);

    return 0;
}

And the variable changes min of int for unsigned int, always returns 0. https://ideone.com/9TNKLp

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).

3 answers

1

It says here min is the highest possible value:

min = INT_MAX;

Then ask

if (min < elemento)

If min is the greatest possible value ever he will be the least, never enter this if.

If you do the opposite then it works:

if (elemento < min)

I put in the Github for future reference.

In addition the first argument passed in the function should be the amount of elements you will have next, used 8 when actually only has 5, this takes dirt from memory and spoils the comparison.

  • I had put: if (element < min),before, but posted wrong, but does not return the correct entry.

0

The problem is this line here:

if(min < elemento)

I believe the signal is switched. The block of this if is executed only if min for minor that compared the element, but min will never be less than anything else since, by definition, its initial value is as high as possible.

0

2 things.

One is that the signal was switched in if, already said by colleagues, the other is that you provided 5 numbers, but said you had 8, so your loop for tries to access parameters that do not exist.

Call your function so you won’t have trouble:

minimo(5, 5, 3, 7, 12, 6);
  • Looks like it worked now.

  • then just mark as response ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.