Flexible array element (c99) inside structure

I use this code after a while, and it works great, but it gave me some headache to implement it. It uses Flexible Array Member (FAM) as well as Struct Hack. Now that the C99 has the ability to use Variable Length Array (VLA), I wonder how I can take advantage of this part?

typedef struct nO
{
    int oper;              /* some operator */
    int nops;              /* number of args */
    struct nO *ptn[1];     /* expansible array <=== HERE */
} nodoOper;

nodoOper *operator(int o, int n, ...)
{
    va_list ap;
    nodoOper *tn;
    size_t tam;
    int i;

    tam = sizeof(nodoOper) + (n - 1) * sizeof(nodoOper *); /* <=== AND HERE */

    if((tn=malloc(tam))==NULL)
        yyerror("Memory fault (cod. 4)");

    tn->oper = o;
    tn->nops = n;
    va_start(ap, n);
    for(i=0; i<n; i++)
        tn->ptn[i] = va_arg(ap, nodoOper*);
    va_end(ap);
    return tn;
}

(I simplified the whole structure and code here because it uses two more structures that are not important for the question, so maybe there are errors in this example)

Now the structure definition is in the header file (.h), and the code creates a syntax tree for the compiler. How to change an array to use variable length?

Thank! Beco.

Edited: Rollback the last edit to a member of the flexible group.

2- . , :

struct nOp
{
    int oper;             /* some operator */
    int nops;             /* number of args */
    struct nOp *ptn[n];   /* Variable Length Array (VLA) */
};
struct nOp tnop;
struct nOp *tn2;

tn2 = &tnop;
return tn2;

, , . , ?

+1
2

, , , struct hack, aka " ", " ":

typedef struct nO
{
    int oper;
    int nops;
    struct nO *ptn[];  // <== look ma, no index!
} nodoOper;

// skip a bit
// no more (n-1) --------\
tam = sizeof(nodoOper) + n * sizeof(nodoOper *);

struct "".

- :

void foo(int size)
{
    float a[size];               // run-time stack allocation
    printf("%lu\n", sizeof(a));  // and run-time sizeof (yuck)
}

(, , .)

+3

C - " " ( ) "struct hack" C99.

6.7.2.1 ; .


" ". . 6.7.5.2 .

0

All Articles