[英]How can I write that code using stdarg In language C
I need to change that code into another, using library stdarg.我需要使用库 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;
}
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
.因此,假设
x_1
在堆栈上并且*(ptr + 1)
是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:要使用 stdarg.h,函数需要三样东西:
Functions like printf
have a format string that is both a fixed argument and it encodes the number and type of each variable argument.像
printf
这样的printf
有一个格式字符串,它既是一个固定参数,又对每个变量参数的数量和类型进行编码。
For value
, the the first argument n
is a fixed argument and it gives the number of variable arguments.对于
value
,第一个参数n
是一个固定参数,它给出了可变参数的数量。 There isn't a clear way to determine the type of each variable argument for value
.没有明确的方法来确定
value
的每个变量参数的类型。 One option is to make a choice, for example "int", and document the function.一种选择是做出选择,例如“int”,并记录该函数。 Since the operation inside the for-loop is division, maybe float or double makes more sense.
由于 for 循环内部的操作是除法,所以可能 float 或 double 更有意义。
Using stdarg.h is straight-forward in this case.在这种情况下,使用 stdarg.h 是直接的。 Use
va_start
to initialize a va_list
and then use va_arg
to get the value of each variable argument.使用
va_start
初始化一个va_list
,然后使用va_arg
获取每个变量参数的值。
/* 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;
}
This example computes (6/3) + (21/7):此示例计算 (6/3) + (21/7):
int r = value(4, 6, 3, 21, 7);
printf("%d\n", r);
and results in并导致
5
This second example shows that value
can be called by unpacking an array第二个示例显示可以通过解包数组来调用
value
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);
which results in这导致
26
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.