![]() |
VOOZH | about |
Flexible Array Member(FAM) is a feature introduced in the C99 standard of the C programming language.
What must be the size of the structure below?
The size of structure is = 4 + 4 + 4 + 0 = 12
In the above code snippet, the size i.e. length of array "stud_name" isn't fixed and is a FAM. The memory allocation using flexible array members(as per C99 standards) for the above example can be done as:
struct student *s = malloc( sizeof(*s) + sizeof(char [strlen(stud_name)]) );Note: While using flexible array members in structures some convention regarding the actual size of the member is defined. The convention is that the flexible array member does not contribute to the size of the structure itself. Instead, the size of the structure is determined by the other data members plus any memory allocated dynamically for the flexible array.
In the above example, the convention is that the member "stud_name" has a size of the number of characters stored.
For Example, Consider the following structure:
Input : id = 15, name = "Kartik"
Output : Student_id : 15
Stud_Name : Kartik
Name_Length: 6
Allocated_Struct_size: 18
Memory allocation of the above structure:
struct student *s =
malloc( sizeof(*s) + sizeof(char [strlen("Kartik")]));
Its structure representation is equal to:
The below C program shows the implementation of flexible array members.
Student_id : 523 Stud_Name : Cherry Name_Length: 6 Allocated_Struct_size: 19 Student_id : 535 Stud_Name : Sanjayulsha Name_Length: 11 Allocated_Struct_size: 24 Size of Struct student: 12 Size of Struct pointer: 8
Output
Student_id : 523
Stud_Name : SanjayKanna
Name_Length: 11
Allocated_Struct_size: 23
Student_id : 535
Stud_Name : Cherry
Name_Length: 6
Allocated_Struct_size: 18
Size of Struct student: 12
Size of Struct pointer: 8