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

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

问题描述

我试图用可变参数实现函数,但输出垃圾值.我已经提到了这个文章 在尝试自己实现之前.谁能帮我解决这段代码,因为我无法理解这段代码有什么问题.

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

推荐答案

问题在于,您尝试直接访问堆栈上的位置,假定可以在该位置找到您的参数.调用约定是特定于机器的,有时是特定于编译器的,并且是您永远无法依赖的实现细节,因此可能在您假设的堆栈中找不到您的参数.就 C 而言,您的代码只是调用了未定义的行为

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

解决方案:使用 stdarg.h 来访问参数,这就是它的用途.

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天全站免登陆