Blog post is related to structure hacking, its a trick of structure to reduce the size of structure.
We must understand few basic thing before discussing Struct Hack:-
What is char a[0]={'1','2','3','4'};
Its an array but what is the sizeof 'a' and what is the sizeof 'a[0]' .
{
int rollno;
int name_length;
char name[0]; // some compiler provides error so there we can use name[1]
}stdnt;
sizeof stdnt is 4+4+0 = 8 .
When we create an array of zero length then its size is also zero, because size of an array depends upon the index multiplied by the size of type. When we create an array of zero length in structure it must be the last member of structure. This technique is known as "Struct Hack".
Above is the screenshot of a working gcc program.
We must understand few basic thing before discussing Struct Hack:-
What is char a[0]={'1','2','3','4'};
Its an array but what is the sizeof 'a' and what is the sizeof 'a[0]' .
sizeof(a) = 0
sizeof(a[0]) = 1
Now :-
struct student{
int rollno;
int name_length;
char name[0]; // some compiler provides error so there we can use name[1]
}stdnt;
sizeof stdnt is 4+4+0 = 8 .
When we create an array of zero length then its size is also zero, because size of an array depends upon the index multiplied by the size of type. When we create an array of zero length in structure it must be the last member of structure. This technique is known as "Struct Hack".
Use Of Struct Hack :-
It is use to create variable,according to the required length at run time.
In the above code name_length is not constant for every student, if we use pointer the 4 byte of data for pointer is also added and this is the benefit of Struct Hack.