C语言变长参数怎么弄


C语言变长参数如何弄啊

        #include <iostream><br />


#include <stdio.h>

#include <stdarg.h>


void func(unsigned count, ...);

int main(void)

{

    func(3, 1, 2, 3);

    return 0;

}


void func(unsigned count, ...)

{

    int next;

    va_list ap;

    vastart(ap, count); // 其次ap必须用宏vastart初始化


    for(int i = 0; i < count; i++)

    {

        //printf("%d: ap = %p, ap = %d, ",i, ap, ap);

        next = vaarg(ap,int); // 使用宏vaarg取得当前ap指向的参数的值,并使ap指向下一个参数

        printf("next = %d\n", next);

    }

    //printf("end: ap = %p\n", ap);

    vaend(ap); // 最后使用宏vaend将指针ap置零

}



我这边有个示例,不过有两个问题我不明白,这个例子中,第一个参数需要传入不定长参数的个数count,如果我不想传可以吗?谁帮我改一下代码


此例是典型的func(int i,...),如果是func(...)这种形式呢?

c语言 基本概念 程序开发

夜袭saber 13 years, 1 month ago

可以,但是你要保证能从这个参数中获取参数个数,就像printf可以根据字符串中的格式码来确定后面的参数个数,因为那个vastart函数需要参数个数的来初始化valist 变量的。

zhang1r answered 13 years, 1 month ago

Your Answer