Deploying the sizeof operator

I tried to implement the sizeof operator. I did it this way.

#define my_sizeof(x) ((&x + 1) - &x)

But it always ended up giving the result as “1” for any data type.

I then had googled for this .. and I found the typecasted code

#define my_size(x) ((char *)(&x + 1) - (char *)&x)

And the code works if it is invented .. I don’t understand why .. This code is also PADDING STRUCTURE excellent.

It also works for

#define my_sizeof(x) (unsigned int)(&x + 1) - (unsigned int)(&x)

Can someone explain how this works if typecasted and if not typecasted?

Thanks in advance.

+23
source share
6 answers

The result of subtracting the pointer is in elements, not in bytes. Thus, the first expression evaluates 1by definition.

, :

#define my_sizeof(x) ((&x + 1) - &x)
#define my_sizeof(x) ((char *)(&x + 1) - (char *)&x)

my_sizeof() .

+26

sizeof C ( ++) (front-end). C ( GCC, typeof), , - (, sizeof((i>1)?i:(1/i)) , i==0, my_sizeof ). . C , wikipedia.

C . . . , .

+6

, "1"

, , . . , char * char, .

+5
#define my_sizeof(x) ((char *)(&x + 1) - (char *)&x)

my_sizeof() :

  • sizeof 1 - 4 ( 4 int)
      my_sizeof(1) - .

  • sizeof (int) - 4 ( 4 int)
      my_sizeof(int) - .

. , int, float, char .., , 2, 3.4, 'A' .., rvalue, a+b foo().

+5
#define my_sizeof(x) ((&x + 1) - &x)

&x ( double x), , 1, , x ( addr_of(x) + 8, - 8Byte).

, x , , , 1 x ( 1 , ).

#define my_size(x) ((char *)(&x + 1) - (char *)&x)

char* , , char (). char 1 , ( )/1 , , , , , x .

- .

+5

# define my_sizeof (x) ((& x + 1) - & x)

& x gives the address of your variable and increments it by one (& x + 1), indicates the address where another variable of type x can be stored. Now, if we do arithmetic at these addresses, for example ((& x + 1) - & x), then he will say that inside ((& x + 1) - & x) the address range 1 variable of type x can be saved.

Now, if we specify this amount of memory with (char *) [since the size of char is 1 byte, and the char * increment will move with only one byte), we get the number of bytes of type x consumes

-2
source

All Articles