The size of a structure in C is the sum of the sizes of its members. The size of a structure type can be determined using the sizeof
operator in C.
For example, the following code declares a structure called person
with three members: a name, an age, and an address:
struct person {
char *name;
int age;
char *address;
};
The size of the person
structure can be determined using the sizeof
operator:
sizeof(struct person);
This will return the size of the person
structure in bytes, which is the sum of the sizes of the name
, age
, and address
members.
The size of a structure can be affected by padding. Padding is added to a structure to ensure that all of its members are aligned on a word boundary. The size of the padding depends on the size of the members of the structure and the alignment requirements of the compiler.
For example, the following code declares a structure called point
with two members: an x-coordinate and a y-coordinate:
struct point {
int x;
int y;
};
The size of the point
structure is 8 bytes, even though the x
and y
members are only 4 bytes each. This is because the x
and y
members are not aligned on a word boundary, so the compiler adds 4 bytes of padding to the structure.
The size of a structure can be calculated by adding the sizes of its members and the padding. However, it is usually easier to use the sizeof
operator to determine the size of a structure.
Here are some things to keep in mind when calculating the size of a structure:
- The size of a structure is not always equal to the sum of the sizes of its members. This is because of padding.
- The size of a structure can vary depending on the compiler and the target platform.
- The size of a structure can be affected by the alignment requirements of the compiler.