Couldn't implement function with variable arguments

扶醉桌前 提交于 2019-12-12 07:28:31

问题


I was trying to implement function with variable arguments but was getting garbage values as output.I have referred to this article before trying to implement on my own.Could anyone help me out with this code as I am unable to understand what's wrong in this code.

/* va_arg example */
#include <stdio.h>      /* printf */
int FindMax (int n, ...)
{
    int i,val,largest,*p;
    p=&n;
    p+=sizeof(int);
    largest=*p;
    for (i=1;i<n-2;i++)
    {
        p+=sizeof(int);
        val=*p;
        largest=(largest>val)?largest:val;
    }
    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;
}

回答1:


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;
}


来源:https://stackoverflow.com/questions/44585826/couldnt-implement-function-with-variable-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!