Defining elastic/flexible structure in C

后端 未结 2 1563
情歌与酒
情歌与酒 2021-01-26 14:22

I have a task to do and the content of the task is:

Please suggest a definition of linked list, which will keep the person\'s name and age in a flexible stru

2条回答
  •  臣服心动
    2021-01-26 15:01

    You are on the right track. However, there is no "flexible structure". You want to use a flexible array member (avail since C99) in a struct:

    typedef struct {
        int age;
        size_t name_size;    // size of the array, not length of the name!
        char name[];         // Flexible array member
    } Structure;
    
    int main(void) {
        Structure *one = malloc(sizeof(*one) + SIZE_OF_NAME_ARRAY);
    }
    

    Note I added a name_size field. C does not store the size of allocated arrays, so you might need this for safe copy/compare, etc. (prevent buffer overflows).

    Using *one makes this term independent of the actual type used. The size of such a struct is as if the arrray had zero elements. However, it will be properly aligned, so it can differ from the same struct without the array.

    Also note that you have to change the allocated size if you use other than a char array to something like sizeof(element_type) * ARRAY_SIZE. This is not necessary for chars, as their size is defined by the standard to be 1.

提交回复
热议问题