c - sizeof 运算符在 C 中的实现

标签 c macros

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

相关文章:

android - 如何在Android Studio中扩展C++宏?

c - 无法识别 time.h 中定义的宏

c - 节点生成中取消引用 NULL 指针警告

c - 我如何知道 cl.exe 应用的是 c89 还是 c99?

c - 如何访问和使用函数中将参数获取为 void * 类型的单个位?

c - 在 C 中定义尽可能最小的宏

c - C语言中printf语句赋给变量时,它存储什么

c - gcc 内在与内联汇编 : which is better?

c# - 错误 "the action was blocked by organization policy ms office 2016"

c - 理解 c 定义宏?