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
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 char
s, as their size is defined by the standard to be 1
.