In C, the following three functions are used to read the value of the variable parameter list.
- Va_start (AP, FMT );
- Vsprintf (info_buf, FMT, AP );
- Va_end (AP );
Use the followingCodeTo demonstrate.
# Include <stdio. h> # include <stdlib. h> # include <stdarg. h> int testfunc (INT flag, const char * FMT ,...) {va_list AP; char buffer [1, 4096] = ""; va_start (AP, FMT); vsprintf (buffer, FMT, AP); va_end (AP ); printf ("buffer is % s \ n", buffer); Return 0;} int main (INT argc, char * argv []) {int flag = 2; int age = 25, Weight = 80; char * name = "Xiaoming"; testfunc (flag, "the new student name is [% s], age is [% d], weight is [% d] kg. ", name, age, weight); getch (); Return 0 ;}
After running, you will find that the buffer content is complete and complete.
Analyze What vsprintf (buffer, FMT, AP) does.
Simply put, the FMT string is parsed to read the information of the variable parameter list.
When formatting symbols such as % s are encountered, the corresponding parameter will be searched; if it is another character, the system will continue to read the next one.
The variable parameter list is placed in the stack from right to left. The va_start () function is used to determine the stack address of the last parameter.
FMT also has a length limit, which seems to be 0x804. If it is converted to decimal format, it is 2052 bytes. If it is exceeded, an error is returned.
Note:
1. When Using Variable Parameter List resolution, be sure to read the % C format to be consistent with the subsequent parameter types. Otherwise, the read parameter memory access may be out of bounds.
2. If the printed variables are implemented by macro definition, for example, # define flag 1, how can we print 1 correctly when printing this flag? Here we need to forcibly convert to the desired type for printing. It should be printf ("flag is % d ",(INT)Flag );