Defining elastic/flexible structure in C

后端 未结 2 1562
情歌与酒
情歌与酒 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.

    0 讨论(0)
  • 2021-01-26 15:05

    my guess: a flexible struct would be one that could handle any age and any name.

    A unsigned int field would handle any age (within reason).

    A char * field would handle any name.

    The struct itself would be:

    struct nameAge { unsigned int age;  char * pName; };  
    

    an instance of the struct would be:

    struct nameAge myNameAge;
    

    Setting the age field would be:

    myNameAge.age = ageValue;
    

    Setting the name field would be:

    myNameAge.name = malloc( numCharactersInName+1 );
    strcpy( myNameAge.name, nameString );
    

    How the code obtained the ageValue for age and/or the characters for NameString is up to the programmer to decide/implement.

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