在 C 中实现 sizeof 运算符

implementation of sizeof operator in C

我试图实现这个问题中给出的内容。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;
}

但是当我编译时出现以下错误。

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))

您的宏正在尝试获取某个类型的地址。您可以通过在其中包含一个带有局部变量的整个块来使宏更长(但这样宏就无法按您想要的方式工作)或者只对变量而不是类型使用宏。

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

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