【C和指標】不定參數

來源:互聯網
上載者:User

一,不定參數執行個體

#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);}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.