一,不定參數執行個體
#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);}