我该如何编写一个函数,它使用可变数量的参数(整数)并使用stdargs输出它们?(How can I write a function that takes a variable number of

编程入门 行业动态 更新时间:2024-10-25 14:33:10
我该如何编写一个函数,它使用可变数量的参数(整数)并使用stdargs输出它们?(How can I write a function that takes a variable number of arguments (integers) and output them using stdargs?)

该程序接受有限数量的整数并使用va_arg提供的宏输出它们。 (stdargs)

#include <stdlib.h> #include <stdarg.h> #include <stdio.h> void main() { foo(5,3,4); } void foo(int i,...){ va_list argp; va_start(argp,i); int p; while ((p = va_arg(argp,int))!= NULL)printf("%d",p); va_end(argp); }

但是,虽然没有出现编译/语法错误,但我没有得到我想要的输出。 我在bash上运行它:

我如何解决我的程序,所以我得到:5,3,4?

This program accepts a finite amount of integers and outputs them using a macro provided by va_arg. (stdargs)

#include <stdlib.h> #include <stdarg.h> #include <stdio.h> void main() { foo(5,3,4); } void foo(int i,...){ va_list argp; va_start(argp,i); int p; while ((p = va_arg(argp,int))!= NULL)printf("%d",p); va_end(argp); }

However although no compiltation/syntax errors arise I do not get the output I want. I get this running on bash:

How can I fix my program so I get: 5,3,4?

最满意答案

您需要传递一个明确的最后一个值并停止,因为va_arg无法检测参数的结尾。

#include <stdarg.h> #include <stdio.h> void foo(int i, ...) { va_list argp; va_start(argp, i); do { printf("%d\n", i); } while ((i = va_arg(argp, int)) != -1); va_end(argp); } int main() { foo(5, 3, 4, -1); return 0; }

输出:

5 3 4

You need to pass an explicit last value and stop on that, because va_arg is not able to detect the end of the arguments.

#include <stdarg.h> #include <stdio.h> void foo(int i, ...) { va_list argp; va_start(argp, i); do { printf("%d\n", i); } while ((i = va_arg(argp, int)) != -1); va_end(argp); } int main() { foo(5, 3, 4, -1); return 0; }

Output:

5 3 4

更多推荐

本文发布于:2023-04-29 02:13:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1334581.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   我该   数量   参数   一个函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!