Original: Step-by-step write algorithm (variable parameter)
"Disclaimer: Copyright, welcome reprint, please do not use for commercial purposes. Contact mailbox: feixiaoxing @163.com "
Variable parameters are a feature of C language programming. In our general programming, the number of parameters of the function is determined, predetermined. However, there is a part of the function, its number is indeterminate, the length is not necessarily, what is the secret in the middle?
In fact, we can recall which functions are functions of variable parameters? In fact, it is sprintf, printf and so on function. So what are the rules of these functions? The key is above the string. We can give an example to see
void Test () {printf ("%s, value =%d\n", "Hello", 10);}
The test function is also a simple print function. So what's special about this function, which is that%s,%d, and later characters are one by one, so how many of these characters, and how many arguments are left after the first argument? So how do you get the address of the back argument? We can recall how the stack is generally handled by stacks,
/** stack space:** parameter 3 | up* parameter 2 |* parameter 1 v down*/
Because the parameters are pressed from right to left, the address of the latter parameter is processed according to the "%" in turn. Now we can write a function of printint printing int data, first create a frame,
void Printint (char* buffer, int data, ...) {return;}
Then verify that there is%d in the buffer parameter, and if one of these characters is present, you need to print an integer.
void Printint (char* buffer, int data, ...) {static char Space[1024];char temp[32];int* start;int count;if (NULL = = buffer) Return;memset (space, 0, 1024x768); memset (temp , 0, +); start = (int*) &buffer;count = 0;while (Buffer[count]) {if (!strncmp (&buffer[count], "%d", strlen ("%d"))) {Start ++;itoa (*start, temp, ten); strcat (space, temp); count + = 2;continue;} Space[strlen (space)] = Buffer[count];count + +;} memset (buffer, 0, strlen (buffer)), memmove (buffer, space, strlen (space)); return;}
To verify that our function is correct, you can write a test function to verify that
void display () {char buffer[32] = {"%d%d%d%d\n"}; Printint (buffer, 1, 2, 3, 4);p rintf (buffer);
Step-by-step write algorithm (variable parameters)