Couldn't implement function with variable arguments

前端 未结 1 1342
别跟我提以往
别跟我提以往 2021-01-29 12:32

I was trying to implement function with variable arguments but was getting garbage values as output.I have referred this article before trying to implement on my own.Could anyon

相关标签:
1条回答
  • 2021-01-29 13:19

    The problem is that you try to access locations on the stack directly where you assume to find your arguments. Calling conventions are machine- and sometimes compiler-specific and an implementation detail you can never rely on, so probably your arguments are not found on the stack where you assume they are. In terms of C, your code just invokes undefined behavior

    Solution: use stdarg.h for accessing the arguments, that's what it's there for.

    #include <stdio.h>      /* printf */
    #include <stdarg.h>
    
    int FindMax (int n, ...)
    {
        va_list ap;
        int i,val,largest;
    
        va_start(ap, n); // <- ap is the argument pointer, this initializes it
                         //    based on the last non-variadic argument.
    
        largest=0;
        while (n--)
        {
            val = va_arg(ap, int); // <- fetch argument and advance pointer
            largest=(largest>val)?largest:val;
        }
        va_end(ap); // done with argument pointer
    
        return largest;
    }
    int main ()
    {
        int m;
        m= FindMax (7,702,422,631,834,892,104,772);
        printf ("The largest value is: %d\n",m);
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题