1

我正在尝试编写一个使用具有可变数量参数的函数的程序。另一个任务是分别打印每个函数调用的所有参数。代码如下:-

#include<stdio.h>
#include<stdarg.h>
#include<string.h>
int mul(int x,...);
int main()
{
int a=1,b=2,c=3,d=4,x;
printf("The product of %d is :%d\n",a,mul(1,a));
printf("The product of %d, %d is :%d\n",a,b,mul(2,a,b));
printf("The product of %d, %d, %d is :%d\n",a,b,c,mul(3,a,b,c));
printf("The product of %d, %d, %d, %d is :%d\n",a,b,c,d,mul(4,a,b,c,d));
return 0;
}
int mul(int x,...)
{
    int i,prod=1;
    va_list arglist;
    va_start(arglist, x);
    for(i=0;i<x;i++)
    {   
        prod*=va_arg(arglist,int);
    }
    printf("\n");
    for(i=0;i<x;i++)
    {   
        printf("The argument is %d\n",va_arg(arglist,int));
    }
    va_end(arglist);
    return prod;
}

该程序的输出如下:-

上述程序的输出

另一段代码是:-

#include<stdio.h>
#include<stdarg.h>
#include<string.h>
int mul(int x,...);
int main()
{
int a=1,b=2,c=3,d=4,x;
printf("The product of %d is :%d\n",a,mul(1,a));
printf("The product of %d, %d is :%d\n",a,b,mul(2,a,b));
printf("The product of %d, %d, %d is :%d\n",a,b,c,mul(3,a,b,c));
printf("The product of %d, %d, %d, %d is :%d\n",a,b,c,d,mul(4,a,b,c,d));
return 0;
}
int mul(int x,...)
{
    int i,prod=1;
    va_list arglist;
    va_start(arglist, x);
    for(i=0;i<x;i++)
    {   
        prod*=va_arg(arglist,int);
    }
    printf("\n");
    va_end(arglist);
    va_start(arglist,x);
    for(i=0;i<x;i++)
    {   
        printf("The argument is %d\n",va_arg(arglist,int));
    }
    va_end(arglist);
    return prod;
}

输出如下:-

第二个输出

为什么会有这种差异?有什么帮助吗?

4

2 回答 2

2

在第一个示例中,您缺少两行:

va_end(arglist);
va_start(arglist,x);

这意味着在进行乘法之后,您正在读取参数末尾的内容。显示的值是堆栈上发生的任何值。

于 2013-01-18T14:51:55.100 回答
0

va_arg(va_list ap, type) 检索参数列表中的下一个参数。因此,在第一个代码中,您在一个循环之后使用参数。您可以使用以下代码代替第二个代码,该代码打印参数并在单个循环中维护乘法

int mul(int x,...)

{
    int i,m,prod=1;
    enter code here
    va_list arglist;
    enter code here
    va_start(arglist, x);
    for(i=0;i<x;i++)
    {   
        m=va_arg(arglist,int);
        prod*=m
        printf("The argument is %d\n",m);
    }
    printf("\n");

    return prod;
}
于 2013-01-18T15:18:30.160 回答