Here is an implementation.
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)
- Is sizeof for a struct equal to the sum of sizeof of each member?
- sizeof operator in C
- Why does sizeof(x++) not increment x in C?
- Do not use sizeof for array parameters
- Anything written in sizeof() is never executed in C
- Operands for sizeof operator
- sizeof() for Floating Constant in C
- How to find size of array in C/C++ without using sizeof ?
- Difference between strlen() and sizeof() for string in C
- Implement your own itoa()
- How to implement Min Heap using STL?
- How to implement our own Vector Class in C++?
- Using class to implement Vector Quantities in C++
- How to implement user defined Shared Pointers in C++
- Implement your own tail (Read last n lines of a huge file)
Improved By : romeosaurabh