How will implement Your Own sizeof in C

In C, the sizeof operator returns the size in bytes of a variable or data type. We can implement our own version of sizeof using pointer arithmetic. The concept is based on the fact that when we increment a pointer by 1, it moves by the size of the data type it points to.

Syntax

#define my_sizeof(variable) (char *)(&variable+1)-(char*)(&variable)

How It Works

The implementation uses pointer arithmetic −

  • &variable gives the address of the variable
  • &variable+1 gives the address after one complete element
  • Casting both to (char*) makes the subtraction return bytes
  • The difference gives us the size in bytes

Example

Here's how to implement and use our custom sizeof macro −

#include <stdio.h>

#define my_sizeof(type) (char *)(&type+1)-(char*)(&type)

int main() {
    int x = 10;
    char y = 'f';
    double z = 254748.23;
    float w = 3.14f;
    
    printf("Size of int x: %ld bytes<br>", my_sizeof(x));
    printf("Size of char y: %ld bytes<br>", my_sizeof(y));
    printf("Size of double z: %ld bytes<br>", my_sizeof(z));
    printf("Size of float w: %ld bytes<br>", my_sizeof(w));
    
    /* Comparison with standard sizeof */
    printf("\nUsing standard sizeof:<br>");
    printf("sizeof(int): %ld bytes<br>", sizeof(int));
    printf("sizeof(char): %ld bytes<br>", sizeof(char));
    printf("sizeof(double): %ld bytes<br>", sizeof(double));
    printf("sizeof(float): %ld bytes<br>", sizeof(float));
    
    return 0;
}
Size of int x: 4 bytes
Size of char y: 1 bytes
Size of double z: 8 bytes
Size of float w: 4 bytes

Using standard sizeof:
sizeof(int): 4 bytes
sizeof(char): 1 bytes
sizeof(double): 8 bytes
sizeof(float): 4 bytes

Key Points

  • We use a macro because the data type is determined at compile time
  • Casting to (char*) ensures byte-level arithmetic since char is always 1 byte
  • This technique works for any variable, including arrays and structures
  • The result matches the standard sizeof operator

Conclusion

Our custom sizeof implementation demonstrates how pointer arithmetic works in C. By calculating the difference between consecutive memory addresses, we can determine the size of any data type, providing the same functionality as the built-in sizeof operator.

Updated on: 2026-03-15T10:36:33+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements