Turn from: http://book.51cto.com/art/200902/109025.htm
transfer of 5.4.2 variable length parameters
The previous section describes how to create a function with variable-length parameters and how to read variable-length arguments, which are done within a function, and this section describes a method of passing a variable-length argument list as a parameter to another function.
The function family of variable-length parameter transfer is as follows:
#include <stdarg.h>
int vprintf (const char *format, va_list AP);
int vfprintf (FILE *stream, const char *format, va_list AP);
int vsprintf (char *str, const char *format, va_list AP); |
These functions are completely equivalent to formatted output functions, only in the form of fixed parameters instead of variable length parameters, so that the description of the function is more compact, these functions are often used in variable-length parameter functions within the implementation of the function.
Instance
design function "int Printlog (file* stream, const char* Pformat, ...)", which controls the number and format of subsequent parameters and outputs in the file stream stream, according to the contents of the string format. The source program is shown in code 5-17:
Code 5-17 passing variable-length parameter instances (section from/code/chapter5/print1.c)
#include <stdarg.h>
#include <stdio.h>
int printlog (file* pfile, const char * pformat, ...)
{
va_list _va_list;
Char szbuf[1024];
if (Pformat = null | | pfile = null) return-1; /* Judge whether the pointer is correct * * *
va_start (_va_list, pformat); /* Initialization variable-length parameter list * *
vsprintf (szbuf, Pformat, _va_list); /* Transfer Variable length parameter * *
va_end (_va_list); /* End use variable length parameter list * *
fputs (szbuf, pfile); /* Output to file stream *
/return 0;
}
void Main ()
{
printlog (stderr, "[%s][%s][%d][%c]\n", "This", "is", 5, ' a ');
Printlog (stderr, "error[%p][%.2f][%x]\n", NULL, 3.123, MB);
|
Compiling and running code 5-17:
# make Print1
cc-o print1.c -o print1
#/print1
[this][is][5][a]
error[00000000][3.12][64 ] |
"Practical experience" for pointer type parameters, it is best to judge whether it is empty at the entrance of the function to avoid null pointers referencing errors. such as the bold part of code 5-17.