我如何使用stdarg在C语言中编写该代码 [英] How can I write that code using stdarg In language C
问题描述
我需要使用stdarg库将该代码更改为另一个代码.代码:
I need to change that code into another, using library stdarg. Code:
int value(int n, int x_1, ...)
{
int result = 0;
int* ptr = &x_1;
for (int i = 0; i < n / 2; i++)
{
result += ((*ptr) / (*(ptr + 1)));
ptr += 2;
}
return result;
}
推荐答案
关于如何将参数传递给函数的详细信息是调用约定".根据平台,语言和编译器的不同,规则可能很复杂.因此,假设 x_1
在堆栈中并且 *(ptr + 1)
是 x_1
之后的第一个参数是不安全的.stdarg.h的目的是提供一种可迭代的方式来遍历变量参数.
The details of how arguments are passed to a function is the "calling convention." Depending on platform, language, and compiler, the rules can be complex. So it is not safe to assume the x_1
is on the stack and *(ptr + 1)
is the first argument after x_1
. The purpose of stdarg.h is to provide a portable way to iterate through the variable arguments.
要使用stdarg.h,一个函数需要三件事:
To use stdarg.h, a function needs three things:
- 至少一个固定参数
- 确定可变参数数量的方法
- 一种确定每种可变摆饰类型的方法
像 printf
这样的函数具有既是固定参数又是固定参数的格式字符串,并且它编码每个可变参数的数量和类型.
Functions like printf
have a format string that is both a fixed argument and it encodes the number and type of each variable argument.
对于 value
,第一个参数 n
是固定参数,它给出了可变参数的数量.没有明确的方法来确定 value
的每个变量参数的类型.一种选择是进行选择,例如"int",并记录功能.由于for循环内部的运算是除法运算,因此也许进行float或double运算更有意义.
For value
, the the first argument n
is a fixed argument and it gives the number of variable arguments. There isn't a clear way to determine the type of each variable argument for value
. One option is to make a choice, for example "int", and document the function. Since the operation inside the for-loop is division, maybe float or double makes more sense.
在这种情况下,使用stdarg.h是直接的.使用 va_start
初始化 va_list
,然后使用 va_arg
获取每个变量参数的值.
Using stdarg.h is straight-forward in this case. Use va_start
to initialize a va_list
and then use va_arg
to get the value of each variable argument.
/* value inputs n variable arguments, call them x_i, of type int
* and returns the value
*
* (x_0 / x_1) + (x_2 / x_3) + ...
*
* n must be even
* the division is integer division
*/
int value(int n, ...)
{
int result = 0;
va_list ap;
va_start(ap, n);
for (int i = 0; i < n/2; ++i) {
int a = va_arg(ap, int);
int b = va_arg(ap, int);
result += a/b;
}
va_end(ap);
return result;
}
示例呼叫
此示例计算(6/3)+(21/7):
Example Calls
This example computes (6/3) + (21/7):
int r = value(4, 6, 3, 21, 7);
printf("%d\n", r);
并得到
5
第二个示例表明,可以通过解压缩数组来调用 value
This second example shows that value
can be called by unpacking an array
int a[] = {49, 7, 64, 8, 121, 11};
int r = value(6, a[0], a[1], a[2], a[3], a[4], a[5]);
printf("%d\n", r);
结果
26
这篇关于我如何使用stdarg在C语言中编写该代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!