简体   繁体   中英

implementation of sizeof operator in C

I tried to implement what is given in this question. sizeof implementation

#include <stdio.h>
#include <stdint.h>

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

int main()
{
    printf("Size of int   %d \n",my_sizeof(int));

    return 0;
}

However when I compile I get the following error.

test.c:10:44: error: expected expression before ‘int’
     printf("Size of int   %d \n",my_sizeof(int));
                                            ^
test.c:5:35: note: in definition of macro ‘my_sizeof’
 #define my_sizeof(type) ((char*)(&type + 1)-(char*)(&type))
                                   ^
test.c:10:44: error: expected expression before ‘int’
     printf("Size of int   %d \n",my_sizeof(int));
                                            ^
test.c:5:54: note: in definition of macro ‘my_sizeof’
 #define my_sizeof(type) ((char*)(&type + 1)-(char*)(&type))
                                                      ^
((char*)(&int + 1)-(char*)(&int))

Your macro is trying to take the address of a type. You could either make the macro a lot longer by including a whole block in it with a local variable (but then the macro wouldn't work how you want) or just only use the macro on variables and not types.

这适用于类型,但不适用于变量:

#define tsizeof(type) (((char *)(1+((type *)0))) - ((char *)((type *)0)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM