How to Find Size of Structure in C: Simple Guide
In C, you can find the size of a structure using the
sizeof operator with the structure's name or a variable of that structure type. For example, sizeof(struct MyStruct) returns the size in bytes of the structure MyStruct.Syntax
The sizeof operator returns the size in bytes of a data type or variable. To find the size of a structure, use:
sizeof(struct StructName)- size of the structure typesizeof(variable)- size of a structure variable
This size includes all members and any padding added by the compiler.
c
sizeof(struct StructName); // or struct StructName var; sizeof(var);
Example
This example shows how to define a structure and find its size using sizeof. It prints the size in bytes.
c
#include <stdio.h>
struct Person {
char name[50];
int age;
double height;
};
int main() {
struct Person p;
printf("Size of struct Person: %zu bytes\n", sizeof(struct Person));
printf("Size of variable p: %zu bytes\n", sizeof(p));
return 0;
}Output
Size of struct Person: 64 bytes
Size of variable p: 64 bytes
Common Pitfalls
Some common mistakes when finding structure size include:
- Assuming the size is just the sum of member sizes; padding may increase size.
- Using
sizeof(pointer_to_struct)instead of the structure itself, which returns pointer size, not structure size. - Not considering alignment and padding added by the compiler.
Always use sizeof(struct StructName) or sizeof(variable) to get the correct size.
c
#include <stdio.h>
struct Data {
char c;
int i;
};
int main() {
struct Data d;
printf("Wrong size (pointer): %zu bytes\n", sizeof(&d)); // size of pointer, usually 4 or 8
printf("Correct size (struct): %zu bytes\n", sizeof(d));
return 0;
}Output
Wrong size (pointer): 8 bytes
Correct size (struct): 8 bytes
Quick Reference
Remember these tips when finding structure size:
- Use
sizeof(struct StructName)orsizeof(variable). - Do not use
sizeof(pointer)to get structure size. - Size includes padding for alignment.
- Use
%zuformat specifier withprintfforsizeofresults.
Key Takeaways
Use the sizeof operator with the structure type or variable to get its size in bytes.
Do not use sizeof on a pointer to a structure to find the structure's size.
Structure size includes padding added by the compiler for alignment.
Use %zu in printf to correctly print the size returned by sizeof.
Always verify structure size especially when working with binary data or memory layouts.