-1

Is there a way to define a variadic size variable in C?

For example, I want to define a table where both the entries of the table and size of each entry should vary in accordance to the configuration file without recompiling the source code.

To dynamically define the entries of the table, we can use malloc in C or new in C++, but how is the size? I mean something like the below

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
    };
};

Thank you very much, and idea please reply me even if you think am ridiculous.

Steve
  • 6,334
  • 4
  • 39
  • 67

1 Answers1

1

C don't manage variable-size type definition. You have to manage it yourself through pointers and memory allocation such as malloc or new.

That's one reason why so many programs have memory leaks...

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
}
Mike
  • 11
  • 4
  • Wrong, for the size: C has VLA, variable length arrays. And then the OP knows about `malloc` and `new`. – Jens Gustedt Aug 17 '15 at 16:36
  • Yes, C has VLA to manage the table size dynamically. (I corrected my answer.) But the question was on the table entries, not the table size. – Mike Aug 17 '15 at 16:47