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.
#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</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)); }
size of x: 4 size of y: 1 size of z: 8
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!