How can I Determine the size of a struct in C?
The sizeof() function in the C programming language is used to calculate the total number of bytes allocated by the data type and variable. In C, a structure’s size is equal to the total size of each of its constituent parts, with any extra padding that might be necessary for alignment reasons.
Syntax
The sizeof() in C can be used to calculate a struct’s size in bytes. The following syntax is used to calculate the size of a struct value:
Change struct_Name to the struct name whose size you want to determine.
Let’s determine the total size of the structure with the following structural definition:
char first_name[20];
char second_name[20];
int my_age;
float result;
};
Four members make up the Person structure: first_name, second_name, my_age, and result. The first_name and second_name members each have a size of 40 bytes, while the age member and result have a size of 4 bytes. The my_Person struct would therefore have a total size of 48 bytes.
Example to Calculate the sizeof() the Structure in C
In C, all you have to do is pair the structure’s name with the sizeof operator to determine the size of the struct. The size of the Person structure, for instance, would be printed using the following code:
struct Person {
char first_name[20];
char second_name[20];
int my_age;
float result;
};
int main() {
printf("Total Size of structure: %d bytes\n", sizeof(struct Person));
return 0;
}
The above example is displayed in the below output:
Note: It’s crucial to remember that if a structure includes any padding bytes, its true size can end up being greater than the total of its parts. To make sure that a structure’s members are aligned on particular memory bounds, padding is added.
Conclusion
In, computing the size of a struct can be determined by applying the sizeof operator and the structure’s name. However, it’s crucial to keep in mind that due to padding supplied for alignment purposes, a structure’s actual size may be greater than the sum of its parts.