【问题标题】:implementation of sizeof operator in CC 中 sizeof 运算符的实现
【发布时间】:2015-09-15 01:49:02
【问题描述】:

我试图实现这个问题中给出的内容。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*)(&amp;int + 1)-(char*)(&amp;int)) int的地址是什么?打败我...

标签: c macros


【解决方案1】:
((char*)(&int + 1)-(char*)(&int))

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-29
      • 1970-01-01
      • 1970-01-01
      • 2018-12-30
      • 1970-01-01
      • 1970-01-01
      • 2018-03-30
      • 2011-07-04
      相关资源
      最近更新 更多