I know this question has been asked many times but sorry, I couldn't find the answer. Below is a function with parameters (how many parameters is unknown). How do I get all parameters and then print them?
我知道这个问题已被多次询问但对不起,我找不到答案。下面是一个带参数的函数(有多少参数未知)。如何获取所有参数然后打印它们?
int func(int a, int b, ...) {
// print the parameters
}
1 个解决方案
#1
1
The short answer is "you don't." C doesn't give you any mechanism to know when the arguments end.
简短的回答是“你没有。” C没有给你任何机制来知道参数何时结束。
If you want to use varargs, you will need to give yourself a mechanism that will tell you how many arguments there are, and how big each one is. To take the most well-known example, printf() requires its first argument to be a formatting string, that tells it about the varargs and their sizes.
如果你想使用varargs,你需要给自己一个机制,告诉你有多少参数,每个参数有多大。举一个最着名的例子,printf()要求它的第一个参数是格式化字符串,告诉它有关varargs及其大小的信息。
If you know that all your arguments are going to be the same size (say, ints), you can design your routine so the first argument is the number of arguments, something like:
如果你知道你的所有参数都是相同的大小(例如,整数),你可以设计你的例程,所以第一个参数是参数的数量,如:
void
my_func (int n_args, ...)
{
va_list ap;
int i;
va_start(ap, n_args);
for (i = 0 ; i < n_args ; i++) {
process(va_arg(ap, int));
}
va_end(ap);
}
#1
1
The short answer is "you don't." C doesn't give you any mechanism to know when the arguments end.
简短的回答是“你没有。” C没有给你任何机制来知道参数何时结束。
If you want to use varargs, you will need to give yourself a mechanism that will tell you how many arguments there are, and how big each one is. To take the most well-known example, printf() requires its first argument to be a formatting string, that tells it about the varargs and their sizes.
如果你想使用varargs,你需要给自己一个机制,告诉你有多少参数,每个参数有多大。举一个最着名的例子,printf()要求它的第一个参数是格式化字符串,告诉它有关varargs及其大小的信息。
If you know that all your arguments are going to be the same size (say, ints), you can design your routine so the first argument is the number of arguments, something like:
如果你知道你的所有参数都是相同的大小(例如,整数),你可以设计你的例程,所以第一个参数是参数的数量,如:
void
my_func (int n_args, ...)
{
va_list ap;
int i;
va_start(ap, n_args);
for (i = 0 ; i < n_args ; i++) {
process(va_arg(ap, int));
}
va_end(ap);
}