C The sizeof Operator

C The sizeof Operator (Beginner → Advanced)
The sizeof operator in C language is used to find the memory size (in bytes) of:
data types
variables
arrays
structures & unions
It is compile-time evaluated and very important for memory management, safety, and interviews.
What is sizeof?
sizeofreturns the number of bytes required to store a data type or object.
Syntax
sizeof Basic Data Types
Typical output (may vary by system):
sizeof Variable Example
- Same as
sizeof(int)andsizeof(float)
sizeof Arrays (Very Important)
Find Number of Elements
- Works only in same scope
sizeof Inside Function (Common Trap)
- Arrays decay to pointers when passed to functions
sizeof(arr)→ size of pointer (4 or 8 bytes)- Always pass size separately
sizeof Pointers
- Pointer size depends on system architecture
- Dereferenced pointer gives data size
sizeof Structures & Unions
Structure
Union
- Size = largest member
sizeof with char and Strings
sizeof≠strlen
sizeof with Expressions
sizeofdoes not evaluate expressions
sizeof on Type Casting
Common Mistakes
- Using
sizeofinstead ofstrlen Usingsizeofinside function for arrays- Assuming same size on all systems
- Forgetting structure padding
Interview Questions (Must Prepare)
What does
sizeofreturn?Is
sizeofa function or operator?Why
sizeof(arr)fails inside function?Difference between
sizeofandstrlen?Does
sizeof(a++)incrementa?
Real-Life Use Cases
Dynamic memory allocation (
malloc)Buffer size calculation
Avoiding buffer overflow
Embedded systems
Portable code
Summary
sizeofreturns memory size in bytes- Evaluated at compile time
- Works differently for arrays & pointers
- Includes padding for structures
- Essential for safe & efficient C programs
