如何在C

时间:2015-08-17 16:14:16

标签: c variables variadic

有没有办法在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
    };
};

非常感谢,即使你觉得很荒谬,也请回复我。

1 个答案:

答案 0 :(得分: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
}