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:

  1. the <stdarg.h> header file must included, introduces new type, called va_list, , 3 functions operate on objects of type, called va_start, va_arg, , va_end.
  2. va_start: macro set arg_ptr beginning of list ap of optional arguments
  3. va_arg: use saved stack pointer, , extract correct amount of bytes type provided
  4. va_end: macro reset ap, 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:

  1. actually function fixed number of arguments followed variable number of arguments. , right-most argument function (in fixed argument list char* b in our function f()) uses initialized viable list ap.
  2. the function f() above fist reads n value 3 (read comment in main). in f(), while(n--) executes 3 time , each time in loop using va_arg() macro retrieves 3 values.
  3. if notice reads first 2 ints double, sending char, 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

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -