代码之家  ›  专栏  ›  技术社区  ›  Shweta

可变函数中的可变数据类型参数

c
  •  2
  • Shweta  · 技术社区  · 15 年前

    4 回复  |  直到 15 年前
        1
  •  2
  •   DigitalRoss    15 年前
    so ross$ expand < variadic.c && cc -Wall -Wextra variadic.c 
    #include <stdio.h>
    #include <stdarg.h>
    
    void f(int, ...);
    struct x { int a, b; } y = { 5, 6 };
    
    int main(void) {
      float q = 9.4;
      f(0, 1.234, &q, "how now", 123, &y);
      return 0;
    }
    
    void f(int nothing, ...) {
      va_list ap;
    
      va_start(ap, nothing);
      double f = va_arg(ap, double);
      float *f2 = va_arg(ap, float *);
      char  *s   = va_arg(ap, char *);
      int    i    = va_arg(ap, int);
      struct x *sx = va_arg(ap, struct x *);
      va_end(ap);
    
      printf("%5.3f %3.1f %s %d %d/%d\n", f, *f2, s, i, sx->a, sx->b);
    }
    so ross$ ./a.out
    1.234 9.4 how now 123 5/6
    
        2
  •  3
  •   AShelly    15 年前

    当然,看看printf的常用用法:

    printf("Error %d: %s", errNum, errTxt);
    
        3
  •  0
  •   pmg    15 年前

    下面是一个无printf的示例(旧版本: http://codepad.org/vnjFj7Uh

    #include <stdarg.h>
    #include <stdio.h>
    
    /* return the maximum of n values. if n < 1 returns 0 */
    /* lying to the compiler is not supported in this version, eg:         **
    **    va_max(4, 8, 8, 8, 8, 8, 8, 8, 8)                                **
    ** or                                                                  **
    **    va_max(4, 2, 2)                                                  **
    /* is a bad way to call the function (and invokes Undefined Behaviour) */
    int va_max(int n, ...) {
      int res;
      va_list arg;
    
      if (n < 1) return 0;
    
      va_start(arg, n);
      n--;
      res = va_arg(arg, int);
      while (n--) {
        int cur = va_arg(arg, int);
        if (cur > res) res = cur;
      }
      return res;
    }
    
    int main(void) {
      int test6 = va_max(6, 1, 2, 3, 4, 5, 6);
      int test3 = va_max(3, 56, 34, 12);
      if (test6 == 6) puts("6");
      if (test3 == 56) puts("56");
      return 0;
    }
    
        4
  •  0
  •   nos    15 年前

    我用一个varadic函数做了一个解压二进制数据的函数,它根据不同的类型 你想要的是“编码/解码”。

    uint32_t a;
    uint16_t b;
    uint16_t c;
    uint8_t *buf = ....;
    
    depickle(buf,"sis",&a,&b,&c);
    

    其中“s”需要一个uint16\u t*,并从中解码2个字节 buf 进入之内 a 作为little endian,'i'表示将4个字节作为little endian解码成'b'

    或将4个字节作为大端字节解码成uint32\t:

    uint32_t a;
    uint8_t buf[] = {0x12,0x34,0x56,0x78};
    depickle(buf,"I",&a);
    

    现在仍有早期版本 here .