
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
How will implement Your Own sizeof in C
To use the sizeof(), we can take the value using a variable x, using &x, it will print the address of it. Now if we increase the value of &x then it may increase in different way. If only one byte is increased, that means it is character, if the increased value is 4, then it is int or float and so on. So by taking the difference between &x + 1 and &x, we can get the size of x.
Here we will use macro as the datatype is not defined in the function. And one more thing, we are casting using (char*) so, it will tell us that how many character type data can be placed in that place. As the character takes one byte of data.
Example
#include <stdio.h> #define my_sizeof(type) (char *)(&type+1)-(char*)(&type) main(void) { int x = 10; char y = 'f'; double z = 254748.23; printf("size of x: %d
", my_sizeof(x)); printf("size of y: %d
", my_sizeof(y)); printf("size of z: %d
", my_sizeof(z)); }
Output
size of x: 4 size of y: 1 size of z: 8
- Related Articles
- Implement your own sizeof operator using C++
- Implement your own itoa() in C
- Write your own memcpy() in C
- Write your own atoi() in C++
- How to write your own header file in C?\n
- Write your own memcpy() and memmove() in C++
- Sizeof operator in C
- Print with your own font using C#
- Write your own strcmp that ignores cases in C++
- How to create your own helper class in Java?
- How to build your own Sqlite database in Python
- How to write your own LaTeX preamble in Matplotlib?
- Build Your Own Botnet
- What is sizeof operator in C++?
- How to start your own podcast on YouTube

Advertisements