我尝试实现这个问题中给出的内容。 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))
您的宏正在尝试获取类型的地址。您可以通过在宏中包含带有局部变量的整个 block 来使宏更长(但这样宏将无法按您想要的方式工作),或者仅在变量而不是类型上使用宏。
关于c - sizeof 运算符在 C 中的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32576430/