可变参函数的用法

可变参函数

#include <stdio.h>
#include <stdarg.h>


void func(int num, ...)
{
    int after = 0;
    
    va_list v; //指针类型  

    va_start(v, num); 
    printf("*v = %d\n", *v);
    
    for(int i = 0; i < num - 1; i++)
    {                
        int res = va_arg(v, int); //返回指向下一个va_list类型的指针
        //printf("after = %d\t, *v = %d \n", res, *v); //出错
        printf("after = %d\n", res);           
    }
    va_end(v);
}


int main()
{
    func( 6,1, 2, 3, 4, 5, 6);   
}
  • 注意:

va_arg返回值的类型为va_list, 不能直接printf输出;

void write_log(const char *fmt, ...){
    va_list va;
    char buf[1024];   
    va_start(va, fmt);
    memset(buf, 0, 1024);
    (void) vsprintf(buf, fmt, va);
    va_end(va);   
    printf("%s: %s", "my_log_prehead", buf);
}

int main()
{
    write_log("%s\n", "hello world!");   
    return 0;
}

vsprintf的用法

#include <string.h>
#include <stdio.h>
#include <stdarg.h>

char buffer[100];

int vspfunc(char *format, ...)
{
    va_list aptr;
    int ret;  
    va_start(aptr, format);
    ret = vsprintf(buffer, format, aptr);
    va_end(aptr);
    return (ret);
}

int main()
{
    int i = 5;
    float f = 27.0;
    char str[50] = "hello world!";

    vspfunc("%d\n%10.3f\n%s", i, f, str);
    printf("%s\n", buffer);

    return 0;
}

输出:

5
    27.000
hello world!

snprintf的用法

#include <stdio.h>

int main ()
{
  char buffer [100];
  int cx;

  cx = snprintf ( buffer, 100, "The half of %d is %d", 60, 60/2 );

  if (cx>=0 && cx<100)      // check returned value

    snprintf ( buffer+cx, 100-cx, ", and the half of that is %d.", 60/2/2 );

  puts (buffer);

  return 0;
}

输出:

The half of 60 is 30, and the half of that is 15.
  • 二、将可变个参数(…)按照format格式化成字符串,然后将其复制到str中
#include <stdio.h>
#include <string.h>


int main ()
{
  char str[6];//最小为6
  memset(str, 0, sizeof(str));
  snprintf(str, sizeof(str), "%d", 65535);
  printf("%s\n", str);
  return 0;
}

输出:

65535$

参考:https://blog.csdn.net/slvher/article/details/9881171
https://blog.csdn.net/mj_lee/article/details/80703893

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值