【C和指针】不定参数

一,不定参数实例

#include "stdio.h"
/*函数参数是以数据结构"栈"的形式存取,从右至左入栈.eg:*/
void fun(int a, ...)
{
	int *temp =&a;
	temp++;
	int i;
	for (i = 0; i < a; ++i)
	{
		printf("%d\n",*temp);
		temp++;
	}
}

 

int main()
{
	int a = 1;
	int b = 2;
	int c = 3;
	int d =4;
	fun(4, a, b, c, d);
	
	return 0;
}
二,va_list的使用

        va_start使argp指向第一个可选参数。

        va_arg返回参数列表中的当前参数并使argp指向参数列表中的下一个参数。

        va_end把argp指针清为NULL。

        函数体内可以多次遍历这些参数,但是都必须以va_start开始,并以va_end结尾

#include <stdio.h>
#include <string.h>
#include <stdarg.h>
int demo( char *msg, ...)
{
	va_list  argp;
	int argno = 0;
	char *para;
	va_start(argp, msg);
	while (1)
	{
		para = va_arg(argp,char*);
		if (strcmp(para, "") == 0)
			break;
		printf("Parameter #%d is:%s\n", argno, para);
		argno++;
	}
	va_end( argp );
	return 0;
}
int  main( void )
{
	demo("DEMO", "This", "is", "a", "demo!","");
}

三,自定义使用


#include <stdio.h>
#include <string.h>
#include <stdarg.h>
void myprintf(char *fmt, ...)
{
	char *pArg = NULL;
	char c;
	pArg =(char *)&fmt;
	pArg+=sizeof(fmt);

	do{//判断每个字符,直到整个语句结束
		c = *fmt;
		if(c!='%')
			putchar(c);
		else
		{
			switch(*++fmt)
			{
				case 'd':
					printf("%d",*((int *)pArg));
					break;
			}
			pArg += sizeof(int);
		}
		++fmt;
	}while(*fmt !='\0');
	pArg = NULL;	//va_end
	
}
int  main( void )
{
	myprintf("the fist : %d\nthe secound : %d\n",1,2);
}

四,详细说明

        在VC++6.0的include有一个stdarg.h头文件,有如下几个宏定义:
            #define   _INTSIZEOF(n) ((sizeof(n)+sizeof(int)-1)&~(sizeof(int) - 1) )
            #define   va_start(ap,v) ( ap = (va_list)&v + _INTSIZEOF(v) ) //第一个可选参数地址
            #define   va_arg(ap,t) ( *(t *)((ap += _INTSIZEOF(t)) - _INTSIZEOF(t)) ) //下一个参数地址
            #define   va_end(ap) ( ap = (va_list)0 ) // 将指针置为无效
#include <iostream>

#include <stdarg.h>

 

const int N=5;

using namespace std;

 

void Stdarg(int a1,...)

{

    va_list argp;

    int i;

    int  ary[N];

 

    va_start(argp,a1);

    ary[0]=a1;

    for(i=1;i< N;i++)

       ary[i]=va_arg(argp,int);

    va_end(argp);

    for(i=0;i< N;i++)

       cout<<ary[i]<<endl;

}

 

void main()

{

    Stdarg(5,12,64,34,23);

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值