Previously when C99 had not introduced flexible array people used the technique of struct hack to create a flexible length member. The struct hack technique gives permission to the user to create a variable length member in the structure.
In the struct hack techniques, we need to create an array whose length is 0 (some compiler does not support the 0 size array). When we create a zero-size array then structure becomes the incomplete type. Basically, an incomplete type structure is a type that has a lack of information about its members.
Let’s take an example to understand the techniques of struct hack,
As I have mentioned above, if we create an incomplete type member in the structure, the structure becomes incomplete types and this technique is called struct hack.
In the below structure I am creating a character array to store student name, I am giving the length of the array 0 (some compiler does not support 0 length array, in that scenario we have to take the length of the array 1).
typedef struct { int RollNumber; int TotalMarks; char Name[0]; } sStudentInfo;
What is the size of the struct hack?
When we calculate the size of the structure then we found that the compiler does not include the size of the 0 length array (Name[0]). So if we assume the size of the integer is 4 bytes, the size of the structure becomes (Here we assume alignment is 4 bytes) 8 bytes.
sizeof(sStudentInfo) = sizeof(RollNumber)+ sizeof(TotalMarks) + sizeof(Name) ;
So output will be 4 + 4 + 0 = 8 bytes.
Sample program to calculate the size of the structure
In the below example code I am calculating the size of the structure which contains 0 length array members.
#include <stdio.h> //Structure in c typedef struct { int RollNumber; //Size of int 4 bytes float Fees; //Size of float 4 bytes int TotalMarks; //Size of int 4 bytes char Name[0]; //Size of int 0 bytes } sStudentInfo; int main() { printf("Size of structure = %d\n",sizeof(sStudentInfo)); return 0; }
Output: Size of structure = 12
If you want to learn more about the c language, here 10 Free days (up to 200 minutes) C video course for you.
Why is struct hack required?
Let’s take an example to understand the above question. First I want to declare a structure that contains the information (price, name, expiry date ..etc) of medicine.
typedef struct { int Price; int ExpiryYears; char Name[MaxSize]; } sMedicineInfo;
In the above structure, the name of the medicine should be dynamic. If the name of the medicine is less than MaxSize, it causes memory loss but if the medicine name greater than the MaxSize, your code can crash. With the help of struct hack, we can resolve the above issue and create the dynamic char array to store the medicine name. See the below section ” How to use struct hack in C?”.
Why do not use a pointer?
Using the pointer we can also create the dynamic length array but problem is that in pointers take extra (4 or 8 bytes depending on the system) memory. When we have created a pointer to the structure then we have to explicitly allocate the memory for the pointers but if we used struct hack then there is no need to allocate memory again for the array.
Let’s see an example for better understanding.
Suppose there are two structure one contains ” char * ” and second contains the “0 length array”, both structure is used to store the name and number of characters within the name.
typedef struct { int iLen; char *pcName; }sNameInfo1;
typedef struct { int iLen; char acName[0]; }sNameInfo2
- In sNameInfo1 the character data could be anywhere in memory and pointed by the pcName but in sNameInfo2 character, data is inside the structure.
- If we create a pointer to sNameInfo1 you need to take care of allocating and freeing of character pointer in addition to struct itself but with a pointer to sNameInfo2, we need allocating and freeing the struct itself because everything is packaged together.
See the below example,
//Allocating memory when using sNameInfo1 sNameInfo1 *psInfo1 = malloc(sizeof(sNameInfo1)); psInfo1->pcName = malloc(sizeof(char) * Number of character + 1); //freeing the allocated memory free(psInfo1->pcName); free(psInfo1); //Allocating memory when using sNameInfo2 sNameInfo1 *psInfo2 = malloc(sizeof(sNameInfo1)+(sizeof(char) * Number of character + 1)); //freeing the allocated memory free(psInfo2);
How to use struct hack in C?
In the below program, I have created a struct hack in place of the static array. You can see how struct hack provides you the facility to create a dynamic character array that behaves like a static array and easy to free the allocated memory as compare to the character pointer.
#include<string.h> #include<stdio.h> #include<stdlib.h> // A structure to store employee information typedef struct EmpInformation { int Emp_id; int Salary; char Address[0]; } sEmpInformation; typedef sEmpInformation* psEmpInformation; // Allocate the memory and initialize the structure psEmpInformation ComposeEmpInfo( int salary,int id, const char *pcAddress) { // Allocating memory as per the requirements psEmpInformation psEmpInfo = malloc( sizeof(*psEmpInfo) + sizeof(char) * strlen(pcAddress) + 1); if(psEmpInfo != NULL) { psEmpInfo->Emp_id = id; psEmpInfo->Salary = salary; strcpy(psEmpInfo->Address, pcAddress); } return psEmpInfo; } // Print student details void printEmpInfo(psEmpInformation psEmpInfo) { printf("Emp_id : %d \ Salary : %d \ Address: %s\n", psEmpInfo->Emp_id,psEmpInfo->Salary,psEmpInfo->Address); } // Driver main Code int main() { //variable to store information more than 30 bytes psEmpInformation Amlendra = ComposeEmpInfo(1,100013, "Preet vihar street-abcd ,block abcxyz, New Delhi, India"); if(Amlendra != NULL) { printEmpInfo(Amlendra); free(Amlendra); } //variable to store information less than 30 bytes psEmpInformation Aticleworld = ComposeEmpInfo(13,200013, "New Delhi, India"); if(Aticleworld != NULL) { printEmpInfo(Aticleworld); free(Aticleworld); } return 0; }
Output:
Many places where struct hack makes sense, I am explaining some scenarios where struct hack is very useful.
- Suppose you are working on a file where you need to store the user information. If you are using struct hack, you need to call write function only once to write all the data in the file because structure and character payload packaged together. It is not possible if you create a character pointer in place of the 0 length array.
- Suppose you want to send the data to the server (TCP/IP), the server expects the received message in the form of the data and length. Using the struct hack you can send the whole data in the single call of send (Name of send function could be anything depending on the system) library function. In place of the array if you used pointer then you will need to calls send function twice, otherwise, you will send the address of the pointer in place of the actual data.
- If you will use an array in place of the pointer, you can use memcpy to copy the data from the one object to another one without any culprit.
Recommended Posts for you
- Calculate size of structure without using sizeof the operator.
- structure in C: you should know in depth
- structure padding, you should know.
- What is flexible array in C?
- Best structure padding questions.
- How to access pointer inside a structure in c.
- How to use the structure of function pointer in c language?
- Function pointer in structure.
- Pointer Arithmetic in C.
- Memory Layout in C.
- Union in C, A detailed Guide.
- typedef vs #define in C.
- Macro in C, with example code.
- enum in C, you should know.
- You should know the volatile Qualifier.
- 100 C interview Questions.
- Interview questions on bitwise operators in C
- 10 questions about dynamic memory allocation.
- File handling in C.
- Pointer in C.
- C format specifiers