C The sizeof Operator

C Tutorial

 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

  • pointers

  • structures & unions

It is compile-time evaluated and very important for memory management, safety, and interviews.


 What is sizeof?

sizeof returns the number of bytes required to store a data type or object.

Syntax


sizeof Basic Data Types


 

 Typical output (may vary by system):

int = 4
float = 4
double = 8
char = 1

sizeof Variable Example


 

  •  Same as sizeof(int) and sizeof(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

  •  Includes padding & alignment

Union


 

  •  Size = largest member

sizeof with char and Strings


 

  • sizeofstrlen

sizeof with Expressions

  •  a is not incremented
  • sizeof does not evaluate expressions

sizeof on Type Casting

  •  Casting affects result

 Common Mistakes

  •  Using sizeof instead of strlen
  •  Using sizeof inside function for arrays
  •  Assuming same size on all systems
  •  Forgetting structure padding

 Interview Questions (Must Prepare)

  1. What does sizeof return?

  2. Is sizeof a function or operator?

  3. Why sizeof(arr) fails inside function?

  4. Difference between sizeof and strlen?

  5. Does sizeof(a++) increment a?


 Real-Life Use Cases

  • Dynamic memory allocation (malloc)

  • Buffer size calculation

  • Avoiding buffer overflow

  • Embedded systems

  • Portable code


 Summary

  • sizeof returns memory size in bytes
  •  Evaluated at compile time
  •  Works differently for arrays & pointers
  •  Includes padding for structures
  •  Essential for safe & efficient C programs

You may also like...