【问题标题】:how to define variadic variable in C如何在C中定义可变参数
【发布时间】:2015-08-17 16:14:15
【问题描述】:

有没有办法在 C 中定义可变大小变量?

例如,我想定义一个表,其中表的条目和每个条目的大小都应根据配置文件而变化,而无需重新编译源代码。

要动态定义表的条目,我们可以在 C 中使用 malloc 或在 C++ 中使用 new,但是大小如何?我的意思是像下面这样的

typedef union {
    // the size of x is determined by the configuration file
    typeof(x)  x;
    struct {
    // n, m are read from the configuration file when the program is running
    typeof(x1) x1: n;  
    typeof(x2) x2: m; 
    // Also, the fields should be variadic
    ... //other_variable
    };
};

非常感谢你,如果你觉得很可笑也请回复我。

【问题讨论】:

  • 可能是动态分配的数组?
  • C 和 C++ 在这方面有很大的不同,所以你应该决定你想要哪一个。
  • 语法独角兽没什么意义:-P ...
  • 你不能。从您简短的 sn-p 中,您的代码甚至无法编译。如果您要问的是泛型,则可以改用void *。并手动维护类型信息。
  • 我投票决定将此问题作为题外话结束,因为它询问的内容既不受c 支持,也不受c++ 语言支持。

标签: c variables variadic


【解决方案1】:

C 不管理可变大小的类型定义。您必须通过指针和内存分配(例如mallocnew)自行管理。

这就是为什么这么多程序有内存泄漏的原因之一......

unsigned int n,m;   // n, m are read from the configuration file when the program is running

struct x {
    x1_t * x1;  
    x2_t * x2; 
    ... //other_variables
};

int xread(struct x *decoded, const char *datap, int size)
{
    malloc(x->x1, m);
    if (!x->x1)
        return -1;
    malloc(x->x2, n);
    if (!x->x2) {
        free(x->x1);
        return -1;
    }
    memcpy(x->x1, datap, m);
    memcpy(x->x2, datap+m, n);
    ... // other_variables
    return m+n;//+...
}

int  xwrite(char *bufferp, const struct x *decoded)
{
    // bufferp shall be allocated with at least m+n
    if (x->x1) {
        memcpy(bufferp, x->x1, m);
        bufferp += m;
    }
    if (x->x2) {
        memcpy(bufferp, x->x2, n);
        bufferp += n;
    }
    ... // other_variables
}

【讨论】:

  • 错误,对于大小:C 有 VLA,可变长度数组。然后OP知道mallocnew
  • 是的,C 有 VLA 来动态管理表大小。 (我更正了我的答案。)但问题在于表格条目,而不是表格大小。
猜你喜欢
  • 2014-02-26
  • 1970-01-01
  • 1970-01-01
  • 2014-08-19
  • 2011-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多