pass many arguments to a C function -
this question has answer here:
how can pass many arguments c function? assuming have function:
void f(int n, char* a, char* b, ...)
i want undefined number of char* arguments. how can so?
what needs called variable number of argument functions, can read : 9.9. variable numbers of arguments , essay tutorial.
a short theory in 4 points understand code:
- the
<stdarg.h>
header file must included, introduces new type, called va_list, , 3 functions operate on objects of type, calledva_start, va_arg, , va_end
. va_start:
macro setarg_ptr
beginning of listap
of optional argumentsva_arg:
use saved stack pointer, , extract correct amount of bytes type providedva_end:
macro resetap
, after arguments have been retrieved,va_end
resets pointer null.
this theory not enough below example (as required) understand basic work-flow/ , steps: (read comment 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: initialize `ap` using right-most argument `b` va_start(ap, b); //step3: access vlist `ap` elements using va_arg() n = va_arg(ap, int); //first value in list gives number of ele in list while(n--){ aa = (char)va_arg(ap, int); // notice type, , typecast = va_arg(ap, int); f = (float)va_arg(ap, double); printf("\n %c %d %f \n", aa,i, f); } //step4: work done, should reset pointer null va_end(ap); } int main(){ char* = "aoues"; char* b = "guesmi"; f(2, a, b, 3, 'a', 3, 6.7f, 'b', 5, 5.5f, 'a', 0, 0.1); // ^ `n` count in variable list return 1; }
who runs:
~$ ./a.out 2, aoues, guesmi 3 6.700000 b 5 5.500000 0 0.100000
a brief explanation of code helpful future users:
- actually function fixed number of arguments followed variable number of arguments. , right-most argument function (in fixed argument list
char* b
in our functionf()
) uses initialized viable listap
. - the function
f()
above fist readsn
value3
(read comment in main). inf()
,while(n--)
executes 3 time , each time in loop usingva_arg()
macro retrieves 3 values. - if notice reads first 2
ints
double
, sendingchar, int, float
(notice in main call f()). because auto type promote in case of variable argument list. (read in detail above lisk)
her 1 more useful link msdn: va_arg, va_end, va_start.
(let me know if need more regarding this)
Comments
Post a Comment