Here is an implementation.
#include<stdio.h> #define my_sizeof(type) (char *)(&type;+1)-(char*)(&type;) int main() { double x; printf("%ld", my_sizeof(x)); getchar(); return 0; } |
Type is like a local variable to the macro. &type gives the address of the variable (double x) declared in the program and incrementing it with 1 gives the address where the next variable of type x can be stored (here addr_of(x) + 8, for the size of a double is 8B).
The difference gives the result that how many variables of type of x can be stored in that amount of memory which will obviously be 1 for the type x (for incrementing it with 1 and taking the difference is what we’ve done). Typecasting it into char* and taking the difference will tell us how many variables of type char can be stored in the given memory space (the difference). Since each char requires the only 1B of memory, therefore (amount of memory)/1 will give the number of bytes between two successive memory locations of the type of the variable passed on to the macro and hence the amount of memory that the variable of type x requires.
But you won’t be able to pass any literal to this macro and know their size.
You can also implement using the function instead of a macro, but function implementation cannot be done in C as C doesn’t support function overloading and sizeof() is supposed to receive parameters of all data types.
Note that the above implementation assumes that the size of character is one byte.
Time Complexity: O(1)
Space Complexity: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Is sizeof for a struct equal to the sum of sizeof of each member?
- Difference between sizeof(int *) and sizeof(int) in C/C++
- Implement your own itoa()
- Implement your own tail (Read last n lines of a huge file)
- How to implement our own Vector Class in C++?
- Write your own memcpy() and memmove()
- Write your own strlen() for a long string padded with '\0's
- Making your own Linux Shell in C
- How to write your own header file in C?
- Operands for sizeof operator
- Do not use sizeof for array parameters
- How to find size of array in C/C++ without using sizeof ?
- sizeof() for Floating Constant in C
- sizeof operator in C
- Difference between strlen() and sizeof() for string in C
- Anything written in sizeof() is never executed in C
- Why does sizeof(x++) not increment x in C?
- When should we write our own copy constructor?
- Does C++ compiler create default constructor when we write our own?
- When should we write our own assignment operator in C++?
Improved By : romeosaurabh


