Understanding variable parameters of C language

Source: Internet
Author: User

The prototype of printf () is int printf (const char *fmt, ...); The back of three. Represents a variable for the C language.

So what is a variation? what function does it have?

Arguments are parameters that are uncertain and can be arbitrarily changed as needed.

Let's start with a function that has a fixed argument list:

int swap (int a,int b)

{

int C;

C=a;

A=b;

B=c;

return A;

}

This is a random function, although because it is all local variables so it is not possible to exchange parameters, but the form of this function is very good.

Another example is a variable parameter list function:

void names (int a, ...)

{

......

}

Anyway, it's just a definition, and the contents are omitted. As you can see, the next parameter can be any parameter, but the local variable shows that the values of all parameters are copied to the contiguous memory in the stack at the time of invocation, so there must be an ordinary variable addressing the type and address of the subsequent mutable parameter.

That is, when you use the C-language variable parameter, you need to change the parameter, that is ... Place at the last parameter, and at least one normal parameter before the argument.

Here's an example:

#include <stdarg.h>

#include <stdio.h>


void func1 (const char * str1, ...)

{

Char *pp;


pp = ((char*) &str1) + sizeof (STR1);

printf ("%d\n", * (int*) pp);

pp = pp + sizeof (int);

printf ("%d\n", * (int*) pp);


pp = pp + sizeof (int);

printf ("%s\n", * ((char**) pp));

}


int main ()

{

Func1 ("%d%d%s\n", 4, 5, "Hello World");

return 0;

}

This function is actually wrong because there is a memory alignment problem, but it is sufficient to recognize and understand the mutable parameters.

The const char * str1 here actually points to a string to print out.

Now let's get to the point and discuss it in detail later.


Understanding variable parameters of C language

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.