Declaring Flexible Array Members in structure

I came across this concept while facing one of my interview then thought to share the concept with you all.It may not seem to be big thing for many of us but sometime prove to be handy while declaring variable arrays in  structure.
Any query related to this is highly appreciated.



Flexible array members allow incomplete array struct members without bounds. Consider:
#include 
struct flex {
    int mem; // Flex array must have a named member
    int arrayWoBoundsSpecified[]; // Flex member must be last member
};
struct NotAflex {
    int a[]; // Error: Flex member must be last member
                    // Therefore incomplete type should be complete
    int mem;
};
int main()
{
     size_t len = sizeof(struct flex); 

   // Flexible array members might be useful for getting variable length             information.
   // The struct object "containing" with the flex array cannot be
   // longer than actual underlying object being accessed.
 
   
   struct flex *p = malloc(len + 100);
   // This tends to product a dynamic type.
   // That is it is now "as if":
   // struct {
   //     int mem;
   //     // Assuming sizeof(int) is 2, then 100 / sizeof(int) is 50
   //     int arrayWoBoundsSpecified[50];
   // };
   p->arrayWoBoundsSpecified[49]; // ok

   struct flex *p2 = malloc(len + 80);
   // This is now "as if":
   // struct {
   //     int mem;
   //     // Assuming sizeof(int) is 2, then 80 / sizeof(int) is 40
   //     int arrayWoBoundsSpecified[40];
   // };
   p2->arrayWoBoundsSpecified[39]; // ok

   struct flex *p3 = malloc(len + 3);
   // This is now "as if":
   // struct {
   //     int mem;
   //     // Assuming sizeof(int) is 2, then 3 / sizeof(int) is 1
   //     int arrayWoBoundsSpecified[1];
   // };
   p3->arrayWoBoundsSpecified[0]; // ok

   struct flex *p4 = malloc(len + 1);
   // This is now "as if":
   // struct {
   //     int mem;
   //     // Assuming sizeof(int) is 2, then 1 / sizeof(int) is 0
   //     // The bounds therefore becomes 1
   //     int arrayWoBoundsSpecified[1];
   // };
   //  Even though the bounds became 1, these are undefined
   p4->arrayWoBoundsSpecified[0]; // undefined behavior
   int *pi = &p4->arrayWoBoundsSpecified[1]; // undefined behavior

   struct flex *p5 = malloc(sizeof *p5 + X * sizeof(int)));
   // The previous examples used "nonsense constants" such as
   // 100, 80, etc for the sizes, so p5 is an example with
   // a more realistic form that the malloc would look like.
   //
   // So, sizeof *p5, will give you the sizeof what p5 points to,
   // which is a struct flex, and then since arrayWoBoundsSpecified
   // is type int, we need X times the sizeof that, to get us a int[X].
   //
   // Obviously you'll need to declare and provide/compute a value
   // for X.
}

Comments

Popular posts from this blog