无法用可变参数实现函数 [英] Couldn't implement function with variable arguments

查看:90
本文介绍了无法用可变参数实现函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用可变参数实现函数,但得到的是垃圾值作为输出。我已经提到

  / * va_arg示例* / 
#include< stdio.h> / * printf * /
int FindMax(int n,...)
{
int i,val,largest,* p;
p =& n;
p + = sizeof(int);
最大= * p; (i = 1; i {
p + = sizeof(int);
val = * p;
最大=(最大> val)?最大:val;
}
回报最大;
}
int main()
{
int m;
m = FindMax(7,702,422,631,834,892,104,772);
printf(最大值是:%d \\\
,m);
返回0;
}


问题是,直接访问您在 中找到您的参数的位置。调用约定是机器的,有时是针对编译器的,而且永远不能依赖的实现细节,因此可能在您认为它们的堆栈中找不到您的参数。在C方面,你的代码只是调用未定义的行为

解决方案:使用 stdarg.h

  #include< stdio.h> / * printf * / 
#include

int FindMax(int n,...)
{
va_list ap;
int i,val,最大;

va_start(ap,n); //< - ap是参数指针,它根据最后一个非可变参数初始化它
// //。

最大= 0;
while(n--)
{
val = va_arg(ap,int); //< - 获取参数和前进指针
largest =(最大> val)?最大值:val;
}
va_end(ap); //用参数指针

返回最大;
}
int main()
{
int m;
m = FindMax(7,702,422,631,834,892,104,772);
printf(最大值是:%d \\\
,m);
返回0;
}


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

解决方案

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

这篇关于无法用可变参数实现函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆