Flexible array member (c99) inside a structure

后端 未结 2 1197
北海茫月
北海茫月 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 15:53

    The C name for that construction is "flexible array member" (it might help your searches), or "struct hack" before C99.

    Look at 6.7.2.1 in the Standard; there is example usage in the text.


    You may also be interested in "Variable Length Arrays". See 6.7.5.2 in The Standard.

    0 讨论(0)
  • 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.)

    0 讨论(0)
提交回复
热议问题