Flexible Array Member In C

Flexible Array Member In C

  • Flexible array member is special type of array whose dimension are unspecified.

Syntax-  <data_type> array_name[];

  • They Should be defined at last within structure.
  • There should be one more named variable in addition to flexible array member.
  • The size for this flexible array member is not allocated when the object is instantiated.
 #include <stdio.h>
 struct st {
     int    var_a;
     int    var_b;
     char   flex_arr[];
 };
 int main()
 {
     struct st obj;
     printf("sizeof of obj = %d\n", sizeof(obj));
     return 0;
 } 

Output : sizeof of obj = 8

Why we need it?

Imagine you need a data whose size is not confirmed. It can be a simple string or whole structure content. In that case flexible array member can be helpful.

Because the size for it can be allocated during run-time. The only thing is you should know the maximum size of data which it can be. So, you can allocate memory for it.

Example:

 #include <stdio.h>
 typedef struct {
     int    age;
     int    height;
     char   name[];
 }person;
  
 int main()
 {    
      person *man = (person*) malloc(sizeof(person)+sizeof(char)*7);
      man->age = 30;
      man->height = 160;
      scanf("%s", man->name);
      printf("%d %d %s", man->age, man->height, man->name);
 } 

The same we can assigned the member through a function also

 #include <stdio.h>
 typedef struct {
     int    age;
     int    height;
     char   name[];
 }person;
  
 void insert_data(person *per,int age, int height, char arr[] )
 {
     per=(person*)malloc(sizeof(person)+strlen(arr));
     per->age=age;
     per->height=height;
     strcpy(per->name=arr);
 }
 int main()
 {    
     int age, height;
     scanf("%d %d",&age,&height,);
     person *man = insert_data(man, age, height, "kartik");
     //printing the data of man
     printf("%d %d %s", man->age, man->height, man->name);
     
 } 

Similarly, In flexible array member we can have data of another structure also.

Contributed by :

This article is contribute by Priyanka Singh. She is having very good experience in multiple technologies & also a good mentor. For more information about her, please click here..

Reference:

Leave a Reply

Your email address will not be published. Required fields are marked *