Allocating struct with variable length array member

后端 未结 5 476
醉话见心
醉话见心 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:42

    While you can do this (and it was often used in C as a workaround of sorts) it's not recommended to do so. However, if that's really what you want to do... here's a way to do it with most compilers (including those that don't play nicely with C99 enhancements).

    #define TEST_SIZE(x) (sizeof(Test) + (sizeof(char) * ((x) - 1)))
    
    typedef struct tagTest
    {
        size_t size;
        char a[1];
    } Test;
    
    int elements = 10; // or however many elements you want
    Test *myTest = (Test *)malloc(TEST_SIZE(elements));
    

    The C specifications prior to C99 do not allow a zero-length array within a structure. To work around this, an array with a single element is created, and one less than the requested element count is added to the size of the actual structure (the size and the first element) to create the intended size.

提交回复
热议问题