In the function prototype, the number of parameters is fixed in general, but what to do if you want to receive an indefinite number of parameters at different times? c language Variable parameter list is provided for implementation.
The variable parameter list is implemented by macros, which are defined in the header file of stdarg.h. A va_list type and three macros, va_start, va_arg and va_end, are declared in the header file. When we use the variable parameter list, we need to declare a variable of VA ﹣ list type to be used with these three macros.
VA start (VA list variable name, the last named parameter before the ellipsis): this macro must be called for initialization before variable parameters can be extracted.
Va'arg (va'list variable name, type'of'var): used to extract variables. Type'of'var is the type of extracted variables. Returns the parameter of the corresponding type.
VA end (VA end variable name): after the parameter processing, you must call VA end to do some cleaning.
The following example is taken from c and pointer
Example code:
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<stdarg.h> #include<string.h> float average(int n_value,...) //Average the specified quantity value { va_list var_arg; //Declare the VA list variable int count = 0; float sum = 0; va_start(var_arg, n_value); //Prepare to access variable parameters { for (count = 0; count < n_value; count++) { sum += va_arg(var_arg, int); } va_end(var_arg); //Complete variable parameter processing return sum / n_value; } } int main() { printf("%lf\n", average(6,1,2,3,4,5,6)); system("pause"); return 0; }
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<stdarg.h> #include<string.h> void nstrcpy(char *dest, ...) { va_list pi; //Declare the VA list variable char *p; va_start(pi, dest); while ((p = va_arg(pi, char *)) != NULL) //Extract variables in parameter list by va_arg(pi,char *) { strcpy(dest, p); dest += strlen(p); //Copy one variable to the next } va_end(pi); } int main() { char a[100]; char *b = "asdg"; char *c = "qwewq"; char *d = "aswq"; nstrcpy(a, b, c, d); printf("%s\n", a); system("pause"); return 0; }
Reference link: https://www.2cto.com/kf/201511/449297.html