Defining elastic/flexible structure in C

自作多情 提交于 2019-12-02 11:34:18

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.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!