stdarg

Posted zxx8808

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了stdarg相关的知识,希望对你有一定的参考价值。

typedef char* va_list;

SYNOPSIS
#include <stdarg.h>

void va_start(va_list ap, last);
type va_arg(va_list ap, type);
void va_end(va_list ap);
void va_copy(va_list dest, va_list src);

DESCRIPTION
A function may be called with a varying number of arguments of varying types. The include file <stdarg.h> declares a type va_list and defines three macros for stepping through a list of arguments whose number
and types are not known to the called function.
The called function must declare an object of type va_list which is used by the macros va_start(), va_arg(), and va_end().

va_start()
The va_start() macro initializes ap for subsequent use by va_arg() and va_end(), and must be called first.
The argument last is the name of the last argument before the variable argument list, that is, the last argument of which the calling function knows the type.
Because the address of this argument may be used in the va_start() macro, it should not be declared as a register variable, or as a function or an array type.

va_arg()
The va_arg() macro expands to an expression that has the type and value of the next argument in the call. The argument ap is the va_list ap initialized by va_start(). Each call to va_arg() modifies ap so that
the next call returns the next argument. The argument type is a type name specified so that the type of a pointer to an object that has the specified type can be obtained simply by adding a * to type.

The first use of the va_arg() macro after that of the va_start() macro returns the argument after last. Successive invocations return the values of the remaining arguments.

If there is no next argument, or if type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), random errors will occur.

If ap is passed to a function that uses va_arg(ap,type) then the value of ap is undefined after the return of that function.

va_end()
Each invocation of va_start() must be matched by a corresponding invocation of va_end() in the same function. After the call va_end(ap) the variable ap is undefined. Multiple traversals of the list, each
bracketed by va_start() and va_end() are possible. va_end() may be a macro or a function.

EXAMPLES

This example is a possible implementation of execl():

#include <stdarg.h>

#define MAXARGS 31
/* * execl is called by * execl(file, arg1, arg2, ..., (char *)(0)); */ int execl(const char *file, const char *args, ...) { va_list ap; char *array[MAXARGS +1]; int argno = 0;
va_start(ap, args); while (args != 0 && argno < MAXARGS) { array[argno++] = args; args = va_arg(ap, const char *); } array[argno] = (char *) 0; va_end(ap); return execv(file, array); }

APPLICATION USAGE

It is up to the calling routine to communicate to the called routine how many arguments there are, since it is not always possible for the called routine to determine this in any other way. For example, execl() is passed a null pointer to signal the end of the list. The printf() function can tell how many arguments are there by the formatargument.

 

C语言中可变参数函数实现原理

va_start和va_end使用详解

 

函数参数的传递原理

  函数参数是以数据结构:栈的形式存取,从右至左入栈。

  首先是参数的内存存放格式:参数存放在内存的堆栈段中,在执行函数的时候,从最后一个开始入栈。因此栈底高地址,栈顶低地址,举个例子如下:
void func(int x, float y, char z);
  那么,调用函数的时候,实参 char z 先进栈,然后是 float y,最后是 int x,因此在内存中变量的存放次序是 x->y->z,因此,从理论上说,我们只要探测到任意一个变量的地址,并且知道其他变量的类型,通过指针移位运算,则总可以顺藤摸瓜找到其他的输入变量。
 
va_list 是一个字符指针,可以理解为指向当前参数的一个指针,取参必须通过这个指针进行。
<Step 1> 在调用参数表之前,定义一个 va_list 类型的变量,(假设va_list 类型变量被定义为ap);
<Step 2> 然后应该对ap 进行初始化,让它指向可变参数表里面的第一个参数,这是通过 va_start 来实现的,第一个参数是 ap 本身,第二个参数是在变参表前面紧挨着的一个变量,即“...”之前的那个参数;
<Step 3> 然后是获取参数,调用va_arg,它的第一个参数是ap,第二个参数是要获取的参数的指定类型,然后返回这个指定类型的值,并且把 ap 的位置指向变参表的下一个变量位置;
<Step 4> 获取所有的参数之后,我们有必要将这个 ap 指针关掉,以免发生危险,方法是调用 va_end,他是输入的参数 ap 置为 NULL,应该养成获取完参数表之后关闭指针的习惯。说白了,就是让我们的程序具有健壮性。通常va_start和va_end是成对出现。
 
int printf(const char *fmt,...)
{
	char *str = NULL, *tmpPtr = NULL;
	int size = LINE_LEN; 	/* Arbitrary Starting Size */
	int n,i;
	va_list ap;

	/* Initial allocation of size */
	str = malloc(size);
	if (str == NULL)
		return 0;

	/* Calculate the size required  and allocate space for string */
	while (1)
	{
		va_start(ap,fmt);
		n = vsnprintf(str,size,fmt,ap);
		va_end(ap);

		/* If no error and buffer is enough */
		if ((n > -1) && (n < size))
			break;

		/* See Glibc documentation for the following */
		if  (n > -1)
			size = n+1;			/* glibc 2.1 */
		else
			size *=2;			/* glibc 2.0 */

		tmpPtr = realloc(str,size);
		if (tmpPtr == NULL)
		{
			free(str);
			str = NULL;
			return -1;
		}
		else
			str = tmpPtr;
	}

	/* Write the formatted output to a string */
	va_start(ap,fmt);
	n = vsprintf(str,fmt,ap);
	va_end(ap);

	/* Platform specific output */
	for (i=0;i<n;i++)
		ConsolePutChar((unsigned short)str[i]);

	/* free and return the result */
	free(str);
	return n;
}

  

以上是关于stdarg的主要内容,如果未能解决你的问题,请参考以下文章

STM32G0学习手册——FreeRTOS中使用printf-stdarg.c进行串口打印

stdarg

stdarg.h

关于可变参数列表stdarg

第 16 章 C 预处理器和 C 库(可变参数:stdarg.h)

C stdarg.h