1

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

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

由于我来自 Java,这对我来说很新,我不知道如何在 C 中做到这一点?

提前致谢

4

1 回答 1

5

因为你的函数声明是这样的:

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

您需要的是可变数量的参数函数,您可以阅读:9.9。可变数量的论点是一个很好的论文教程

带有函数 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 中,事情实际上是固定数量的参数,后跟可变数量的参数

于 2013-04-12T09:27:13.083 回答