Home > Backend Development > C++ > body text

How to implement your own sizeof in C

WBOY
Release: 2023-09-14 16:17:08
forward
657 people have browsed it

How to implement your own sizeof in C

To use sizeof(), we can use variable x to get the value, use &x and it will print out its address. Now, if we increase the value of &x, it may increase in a different way. If only one byte is added, that means it is of type character, if the added value is 4, it is of type int or float, and so on. So by calculating the difference between &x 1 and &x, we can get the size of x.

Here, we will use macros because the data type is not defined in the function. One more thing, we use (char*) for type conversion so it will tell us how much character type data we can put at that location. Because the character type occupies one byte of data.

Example

#include <stdio.h>
#define my_sizeof(type) (char *)(&type+1)-(char*)(&type)
main(void) {
   int x = 10;
   char y = &#39;f&#39;;
   double z = 254748.23;
   printf("size of x: %d</p><p>", my_sizeof(x));
   printf("size of y: %d</p><p>", my_sizeof(y));
   printf("size of z: %d</p><p>", my_sizeof(z));
}
Copy after login

Output

size of x: 4
size of y: 1
size of z: 8
Copy after login

The above is the detailed content of How to implement your own sizeof in C. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template