How Do Sizeof and Offsetof in C Work?

The sizeof and offsetof operators in C help you inspect how data is stored in memory.
sizeof returns the memory size (in bytes) of a variable or data type, while offsetof returns the byte offset of a structure member from the start of the structure.
Both operators are essential for memory-safe programming and low-level system design.

In modern C development- especially in embedded systems, drivers, compilers, and performance-heavy applications-understanding memory layouts is crucial. Developers rely on tools like sizeof and offsetof to write safer, predictable, and optimized code.
Yet, many beginners memorize these operators without truly understanding how they impact structure padding, alignment, and memory efficiency.
This guide breaks everything down simply so you can use them confidently in interviews and real projects.

Key Takeaways – sizeof and offsetof in C

  • sizeof → Returns memory size (bytes) of variables, types, arrays, structs.
  • offsetof → Returns byte offset of any struct member.
  • sizeof is compile-time → Safer, avoids runtime errors.
  • offsetof helps understand memory layout → Useful in systems programming.
  • Common use cases → Data serialization, embedded systems, struct alignment, buffer design.
sizeof and offsetof in C

What Is the sizeof Operator in C?

The sizeof operator in C is a compile-time operator that returns the size (in bytes) of any data type, variable, array, pointer, or structure.
It is used by compilers to determine how much memory needs to be allocated for a given object.

Why sizeof Is Evaluated at Compile Time

  • sizeof is processed during compilation, before the program runs.
  • The compiler already knows the memory size of primitive types, structs, and static arrays.
  • Only in the case of variable-length arrays (VLA) does sizeof get evaluated at runtime.

How sizeof Helps Avoid Memory Overflow

  • Prevents manual miscalculations of memory size.
  • Ensures exact buffer allocation using types instead of hardcoded values.
  • Reduces bugs in dynamic memory allocation, pointer arithmetic, and struct handling.

Syntax of sizeof in C

sizeof can be used in two forms:

sizeof(expression);
sizeof(type);

Examples:

sizeof(int);
sizeof(variableName);

Examples of sizeof with Different Data Types

1. sizeof with int, float, double, char

printf("%zu", sizeof(int));     // Typically 4 bytes  
printf("%zu", sizeof(float));   // Typically 4 bytes  
printf("%zu", sizeof(double));  // Typically 8 bytes  
printf("%zu", sizeof(char));    // Always 1 byte (by standard)

2. sizeof with Arrays

int arr[10];
printf("%zu", sizeof(arr));     // Typically 40 bytes (10 × 4)

✔ Helpful for calculating number of elements:

int count = sizeof(arr) / sizeof(arr[0]);

3. sizeof with Pointers

int *ptr;
printf("%zu", sizeof(ptr));     // Typically 8 bytes on 64-bit systems

Note:
sizeof(ptr)sizeof(*ptr)

  • sizeof(ptr) → size of pointer
  • sizeof(*ptr) → size of data it points to

4. sizeof with Structs

struct Data {
    int id;
    char flag;
    double value;
};

printf("%zu", sizeof(struct Data));

Result includes padding added due to alignment.

What Is the offsetof Operator in C?

The offsetof operator, defined in the <stddef.h> header, returns the byte offset (distance in bytes) of a struct member from the beginning of the structure.

offsetof Flowchart

Why Developers Use offsetof

  • Helps inspect internal memory layout of structs
  • Useful in low-level code, serialization, embedded systems, kernel development
  • Enables mapping binary data to struct members safely

Syntax of offsetof

offsetof(struct_name, member);

Example:

offsetof(Person, age);

Example of offsetof with Struct Members

#include <stdio.h>
#include <stddef.h>

struct Person {
    char gender;
    int age;
    double height;
};

int main() {
    printf("%zu\n", offsetof(struct Person, gender));  // 0
    printf("%zu\n", offsetof(struct Person, age));     // Likely 4
    printf("%zu\n", offsetof(struct Person, height));  // Likely 8 or 16
}

Values depend on system padding & alignment strategies.

Why Do C Programmers Use sizeof and offsetof?

1. Memory-Efficient Programming

sizeof helps allocate the exact amount of memory needed.

2. Understanding Padding and Alignment

offsetof shows how the compiler arranges struct members.

3. Secure Buffer Allocation

Avoids magic numbers and reduces overflow risks:

malloc(sizeof(struct Packet));

4. Designing Platform-Independent Structures

sizeof and offsetof ensure structures behave consistently across compilers/architectures.

How Does Memory Layout Affect sizeof and offsetof?

1. Structure Padding

Compilers add padding bytes to align data for performance:

  • A double may require 8-byte alignment
  • Members may shift positions due to padding

Example:

struct A {
    char x;   // 1 byte
    int y;    // 4 bytes, aligned at offset 4
};

2. Alignment Requirements

Memory alignment improves CPU access speed, affecting:

  • struct size (sizeof(struct))
  • offsets of members (offsetof)

3. Compiler Differences

Different compilers may apply:

  • Different padding rules
  • Different default alignments
  • Different struct packing behavior

This is why sizeof and offsetof must not be replaced with hardcoded values.

sizeof vs strlen vs sizeof(struct)

Operator/FunctionWhat It DoesWorks OnReturnsNotes
sizeofMemory size in bytesVariables, types, arrays, structs, pointersCompile-time sizeIncludes padding
strlenLength of string until \0C-stringsCount of charactersRuntime function
sizeof(struct)Size of full structurestruct typesTotal bytesIncludes padding/alignment

Clear, Interview-Ready Explanation

sizeof:

  • Tells how many bytes the compiler allocates.
  • Includes padding.
  • Works on any data type.

strlen:

  • Counts characters until \0.
  • Works only on null-terminated strings.
  • Runtime function, slower.

sizeof(struct):

  • Complete memory footprint including alignment.
  • Useful for serialization, file I/O, and buffers.

If you’d like, I can now expand this into the full 1100-word polished blog body following your new AEO structure.

Exploring sizeof and offsetof in C

c
#include 
#include 

struct Example {
    char a;
    int b;
    double c;
};

int main() {
    // Demonstrating sizeof
    printf("Size of char: %zu bytes
", sizeof(char));
    printf("Size of int: %zu bytes
", sizeof(int));
    printf("Size of double: %zu bytes
", sizeof(double));
    printf("Size of struct Example: %zu bytes
", sizeof(struct Example));

    // Demonstrating offsetof
    printf("Offset of a in struct Example: %zu bytes
", offsetof(struct Example, a));
    printf("Offset of b in struct Example: %zu bytes
", offsetof(struct Example, b));
    printf("Offset of c in struct Example: %zu bytes
", offsetof(struct Example, c));

    return 0;
}
  

Explanation of the Code

Here’s a breakdown of the given C code snippet, which demonstrates the use of the `sizeof` and `offsetof` operators:

  1. This program starts by including the necessary headers, `stdio.h` for input-output functions and `stddef.h` for the `offsetof` macro. These headers provide the essential functionalities used in the program.
  2. It defines a simple struct, `Example`, with three members: a `char`, an `int`, and a `double`. These are fundamental data types in C, representing a character, an integer, and a floating-point number, respectively.
  3. In the `main` function, several `printf` statements showcase the `sizeof` operator’s ability to return the size (in bytes) of each data type and the entire struct. This helps in understanding memory allocation.
  4. Finally, the `offsetof` macro is used to determine the byte offsets of each member from the start of the struct, highlighting how data is aligned within the structure.

Output

Size of char: 1 bytes
Size of int: 4 bytes
Size of double: 8 bytes
Size of struct Example: 16 bytes
Offset of a in struct Example: 0 bytes
Offset of b in struct Example: 4 bytes
Offset of c in struct Example: 8 bytes

Comparison of sizeof and offsetof in C

sizeof vs offsetof: Key Differences

Featuresizeofoffsetof
PurposeGet size of type/variableGet byte position of struct member
ReturnsSize in bytesOffset in bytes
Header RequiredNone<stddef.h>
Operates OnTypes, variables, arrays, structsStruct + struct member
Used InMemory allocationUnderstanding memory layout
Runtime/Compile TimeCompile timeCompile time

Practical Uses of ‘sizeof’ and ‘offsetof’ in C

 

    1. Memory Alignment in Operating Systems (Example: Microsoft)
      Companies like Microsoft employ `sizeof` to ensure that data structures used in their operating systems are aligned correctly for performance optimization. When structures are aligned, the system can access data more efficiently.

      #include <stdio.h>

      struct Process {
      int pid;
      char state;
      double cpu_time;
      };

      int main() {
      printf("Size of Process structure: %lu
      ", sizeof(struct Process));
      return 0;
      }

    2. The output ensures data is allocated optimally:

      Size of Process structure: 16
    1. Data Serialization in Databases (Example: Oracle)
      Oracle databases might use `offsetof` to serialize data structures for storage and transmission. By using `offsetof`, the developers can dynamically calculate where each data element begins in a structure.
      #include <stdio.h>
      #include <stddef.h>

      struct Record {
      int id;
      char name[50];
      float value;
      };

      int main() {
      printf("Offset of name: %lu
      ", offsetof(struct Record, name));
      return 0;
      }

      The output shows the precise position of each field in the structure:

      Offset of name: 4
    1. Embedded Systems Development (Example: Intel)
      Intel uses `sizeof` and `offsetof` in embedded system programming to control memory allocation and access in resource-constrained environments. This helps in optimizing hardware interactions.
      #include <stdio.h>
      #include <stddef.h>

      struct SensorData {
      float temperature;
      float humidity;
      int sensor_id;
      };

      int main() {
      printf("Size of SensorData structure: %lu
      ", sizeof(struct SensorData));
      printf("Offset of humidity: %lu
      ", offsetof(struct SensorData, humidity));
      return 0;
      }

      Outputs aid efficient memory usage and precise data handling:

      Size of SensorData structure: 12

      Offset of humidity: 4

Mastering sizeof and offsetof in C Interview Questions

So you’re curious about some of the more obscure questions surrounding `sizeof` and `offsetof` in C, are you? These concepts might seem tricky at first, but breaking them down through frequently asked questions can shine some light. Let’s dive into it:

  1. What’s the difference between sizeof and allocating memory using malloc?
    The sizeof operator returns the size, in bytes, of a data type or object, which is evaluated at compile-time. In contrast, malloc is used to allocate a specific amount of memory dynamically at runtime. For example:

    size_t size = sizeof(int); // Compile-time size determination
    int *ptr = (int *)malloc(size); // Runtime memory allocation
  2. Why is sizeof(char) always 1 in C?
    In C, the size of a char is defined to be 1 byte, by the standard. This doesn’t necessarily mean 1 byte in the way people often think (8 bits); it’s “1” as a baseline for other data sizes.
  3. Can the value of sizeof be negative?
    No, the value returned by sizeof is of type size_t, which is an unsigned integer type, so it cannot be negative.
  4. Does offsetof work with non-structure types?
    No, offsetof is specifically designed to obtain the offset of a member within a structure, and it doesn’t apply to other types like arrays or primitive data types.
  5. Can you use sizeof to determine the size of a dynamically allocated array?
    No, sizeof doesn’t recognize dynamically allocated arrays. To determine the size, you need to track it separately.
  6. How does offsetof ensure type safety when used?
    offsetof doesn’t directly ensure type safety; it’s a macro that calculates based on field addresses. You need to be cautious and ensure that the offset queried belongs to the intended structure.
  7. Is sizeof evaluated at runtime or compile-time?
    Primarily, sizeof is evaluated at compile-time unless applied to a variable length array, which requires runtime computation.
  8. Why might offsetof lead to undefined behavior in some cases?
    Using offsetof with non-POD (Plain Old Data) structures or on structures with types not fitting standard memory layout rules might lead to undefined behavior, according to the standard.

These questions should provide insight beyond what’s typically covered, allowing you to fill in some knowledge gaps and approach `sizeof` and `offsetof` with confidence. Feel free to experiment and ask more questions as you explore further!

Our AI-powered C compiler is a game-changer for coding enthusiasts! With the C online compiler, you can instantly write, run, and test your code. It streamlines the coding process, offering immediate feedback to help you improve your coding skills with ease. Give it a try today!

Conclusion

Learning about `sizeof and offsetof in C` provides insight into memory management and structure alignments, boosting your coding efficiency. I encourage you to try these concepts yourself—you’ll feel a sense of achievement! For more on programming languages like Java, Python, C, and more, check out Newtum.

Edited and Compiled by

This article was compiled and edited by @rasikadeshpande, who has over 4 years of experience in writing. She’s passionate about helping beginners understand technical topics in a more interactive way.

About The Author