[Talking About] How to obtain the variable parameter list in C Language

Source: Internet
Author: User

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 );

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.