循环(char * c,...)

时间:2013-04-12 09:11:48

标签: c

我是C的新手,我需要遍历例程的参数:

void doSmth(char *c, ...) { //how to print all the elements here? }

由于我来自Java,这对我来说很新,而且我不知道如何在C中这样做?

提前致谢

1 个答案:

答案 0 :(得分:4)

因为您的函数声明如下:

void doSmth(char *c, ...);

您所需要的是可变数量的参数函数,您可以阅读:9.9. Variable numbers of arguments一篇优秀的论文教程

带有函数doSmth()的示例代码其4个步骤,读取注释

//Step1: Need necessary header file
#include <stdarg.h>     
void doSmth( char* c, ...){   
    va_list ap;  // vlist variable
    int n;       // number 
    int i;
    float f;     

   //print fix numbers of arguments
   printf(" C: %s", c);

   //Step2: To initialize `ap` using right-most argument that is `c` 
    va_start(ap, c); 

   //Step3: Now access vlist `ap`  elements using va_arg()
     n = va_arg(ap, int); //first value in my list gives number of ele in list 
     while(n--){
       i = va_arg(ap, int);
       f = (float)va_arg(ap, double); //notice type, and typecast  
       printf("\n %d %f \n", i, f);
    }

    //Step4: Now work done, we should reset pointer to NULL
    va_end(ap); 
}
int main(){
    printf("call for 2");
    doSmth("C-string",  2,    3,   6.7f,  5,   5.5f);
        //              ^ this is `n` like count in variable list 
    printf("\ncall for 3");
    doSmth("CC-string", 3,  -12, -12.7f,-14, -14.4f, -67, -0.67f);
         //             ^ this is `n` like count in variable list
    return 1;
}

它像:

:~$ ./a.out 
call for 2 C: C-string
 3 6.700000 
 5 5.500000 

call for 3 C: CC-string
 -12 -12.700000 
 -14 -14.400000 
 -67 -0.670000 

在C中,事物实际上是固定数量的参数,后跟可变数量的参数