简体   繁体   English

C语言中sizeof运算符的实现

[英]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)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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