C Language: C program to find the size of a structure and why does the structure's area differ from each member's?
C – Find the size of a structure.
The sizeof( ) operator returns the number of bytes needed to store a variable or data type, so on most sytems, sizeof( int ) would yield 4, as would sizeof(number) if number were a variable of type int.
Code:
# include <stdio.h>
struct example {
int a;
char b;
char str_name[20];
double c;
float d;
};
int main() {
struct example e;
printf("Size of example structure: %ld bytes\n", sizeof(e));
printf("\nSize occupied by int a: %d\n",sizeof(e.a));
printf("Size occupied by char b: %d\n",sizeof(e.b));
printf("Size occupied by string str_name: %d\n",sizeof(e.str_name));
printf("Size occupied by double c: %d\n",sizeof(e.c));
printf("Size occupied by float d: %d\n",sizeof(e.d));
return 0;
}
Output:
Size of example structure: 48 bytes Size occupied by int a: 4 Size occupied by char b: 1 Size occupied by string str_name: 20 Size occupied by double c: 8 Size occupied by float d: 4
In the above program, we define a struct called example that contains three members of different types. We then create an instance of this struct, e, and use sizeof() to print the size of the struct.
Why does the structure's area differ from each member's?
The size of a structure is not always equal to the sum of the sizes of its members. Compilers may add padding between members to ensure that they are aligned properly in memory. Alignment requirements can vary depending on the CPU architecture and compiler options. The amount of padding between members can affect the structure's size.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/c-programming-exercises/c-snippets/determine-size-of-structure-and-why-structure-size-is-different-in-c.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics