我该如何编写一个函数,它使用可变数量的参数(整数)并使用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 4You 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更多推荐
发布评论