C语言编译错误:错误:‘->’参数类型无效(有‘int’)

一、编译错误代码:

#include 

int main()
{
    #define offsetof(type, member) ((size_t) &((type *)0->member))

    struct test
    {
    	int a;
    	int b;
    };

    printf("offset of a %d\n", offsetof(struct test, a));
    printf("offset of b %d\n", offsetof(struct test, b));
    return 0;
}

二、错误信息:

test.c:5:57: 错误:‘->’参数类型无效(有‘int’)
     #define offsetof(type, member) ((size_t) &((type *)0->member))
                                                         ^
test.c:13:32: 附注:in expansion of macro ‘offsetof’
     printf("offset of a %d\n", offsetof(struct test, a));
                                ^~~~~~~~
test.c:5:57: 错误:‘->’参数类型无效(有‘int’)
     #define offsetof(type, member) ((size_t) &((type *)0->member))
                                                         ^
test.c:14:32: 附注:in expansion of macro ‘offsetof’
     printf("offset of b %d\n", offsetof(struct test, b));
                                ^~~~~~~~

三、错误原因

运算符"->"的优先级高于强转的优先级,编译器先取0->member的值

四、修改后代码

#include 

int main()
{
    #define offsetof(type, member) ((size_t) &(((type *)0)->member))

    struct test
    {
    	int a;
    	int b;
    };

    printf("offset of a %d\n", offsetof(struct test, a));
    printf("offset of b %d\n", offsetof(struct test, b));
    return 0;
}


你可能感兴趣的:(编译错误记录)