Flexible array member (c99) inside a structure

后端 未结 2 1204
北海茫月
北海茫月 2021-01-25 15:26

I\'ve being using this code a while now, and it works fine, but it gave me some headache to implement it. It uses Flexible Array Member (FAM) aka Struct Hack. Now that C99 has t

2条回答
  •  时光取名叫无心
    2021-01-25 16:00

    Actually, it's not variable-length arrays that you want to use here, but the struct hack, aka "incomplete types", aka the "flexible array member":

    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 *);
    

    Only the last member of a struct may be "flexible".

    Variable-length arrays are a different feature:

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

    (Oh, and these things are called arrays, not matrices.)

提交回复
热议问题