我如何传递多个参数到C函数?假设我有这个功能:
无效F(INT N,字符*一,字符* B,...)我想要的char *参数未定义的数量。我该怎么办呢?
解决方案您需要什么叫可变数量的参数功能,可以读出:的 9.9。可变的参数个数的一个很好的和作文教程。
:四点会帮助你了解我的codeA 短论
这理论是不够的,但下面的例子(如您需要)将帮助你了解基本的工作流程/和步骤:(阅读评论为每4个步骤的)
//第一步:需要必要的头文件#包括LT&;&STDARG.H GT;无效F(第一INT,字符*一,字符* B,...){ va_list的AP; //变量VLIST INT N; //号 字符AA, INT I; 浮F; //参数打印固定号码 的printf(\\ N%D,%S,%S \\ n,第一,A,B); //第二步:初始化`ap`使用最右边的参数为`B` 的va_start(AP,B); //第三步:现在访问VLIST`使用的va_arg ap`元素() N =在va_arg(AP,INT); //我的列表中第一个值给出列表ELE数 而(N - ){ AA =(char)的的va_arg(AP,INT); //通知类型,类型转换 我的va_arg =(AP,INT); F =(浮动)的va_arg(AP,双面); 的printf(\\ n%C%d个%F \\ N,AA,I,F); } //第四步:现在的工作完成后,我们应该重新设置指针为NULL va_end用来(AP);}诠释主(){ 字符* A =Aoues; 字符* B =Guesmi; F(2,A,B,3,'一个',3,6.7f,'B',5,5.5F,A,0,0.1); // ^这是`变量名单N`像数 返回1;}谁来做它运行:
〜$ ./a.out 2,Aoues,Guesmi 3 6.700000 B 5 5.500000 A 0 0.100000一个我的code的简要说明将有利于未来的用户:
其次是变量她是从MSDN多了一个有用的链接:在va_arg中,va_end,va_start中。
(让我知道如果你需要对更多的帮助这个的)
How can I pass many arguments to a C function? Assuming that I have this function:
void f(int n, char* a, char* b, ...)I want an undefined number of char* arguments. How can I do so?
解决方案What you needs is called variable number of argument functions, you can read from : 9.9. Variable numbers of arguments a good and essay tutorial.
A short theory in four points will help you to understand my code:
This theory is not enough but below an example (as you required) will help you to understand basic work-flow/ and steps: (read comment for each 4 steps)
//Step1: Need necessary header file #include <stdarg.h> void f(int first, char* a, char* b, ...){ va_list ap; // vlist variable int n; // number char aa, int i; float f; //print fix numbers of arguments printf("\n %d, %s, %s\n", first, a, b); //Step2: To initialize `ap` using right-most argument that is `b` va_start(ap, b); //Step3: Now access vlist `ap` elements using va_arg() n = va_arg(ap, int); //first value in my list gives number of ele in list while(n--){ aa = (char)va_arg(ap, int); // notice type, and typecast i = va_arg(ap, int); f = (float)va_arg(ap, double); printf("\n %c %d %f \n", aa,i, f); } //Step4: Now work done, we should reset pointer to NULL va_end(ap); } int main(){ char* a = "Aoues"; char* b = "Guesmi"; f(2, a, b, 3, 'a', 3, 6.7f, 'b', 5, 5.5f, 'A', 0, 0.1); // ^ this is `n` like count in variable list return 1; }Who does it runs:
~$ ./a.out 2, Aoues, Guesmi a 3 6.700000 b 5 5.500000 A 0 0.100000A brief explanation of my code will be helpful for future users:
Her is one more useful link from MSDN: va_arg, va_end, va_start.
(let me know if you need more help regarding this)
更多推荐
通过大量的参数传递给C函数
发布评论