Allocating struct with variable length array member

后端 未结 5 460
醉话见心
醉话见心 2020-12-01 22:24

I know I can do new char[n] to create an array of n chars. This works even when n is not a compile time constant.

But lets say

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 22:40

    You can also use the "Length 1 Array" trick. This is in C:

    struct Test {
        size_t size;
        char a[1];
    }
    
    int want_len = 2039;
    struct Test *test = malloc(sizeof(struct Test) + (want_len - 1));
    test->size = want_len;
    

    GCC also supports "0 length" arrays for exactly this purpose: http://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html

提交回复
热议问题