Flexible array member in C-structure

后端 未结 4 1527
自闭症患者
自闭症患者 2020-11-28 14:14

Quoting from the C-std section 6.7.2.1,

struct s { int n; double d[]; };

This is a valid structure declaration. I am looking for some prac

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 14:21

    You can use it to add header fields to dynamically allocated arrays, the most common one of which would be its size:

    struct int_array
    {
        size_t size;
        int values[];
    };
    
    struct int_array *foo = malloc(sizeof *foo + 42 * sizeof *foo->values);
    foo->size = 42;
    
    ...
    
    for(size_t i = 0; i < foo->size; ++i)
        foo->values[i] = i * i;
    

    You could achieve similar results by using an int * member instead and allocating the array seperately, but it would be less efficient both in terms of memory (additional pointer, heap management for 2nd memory block) and runtime (additional indirection, 2nd allocation).

提交回复
热议问题