在C中明确演员

时间:2010-12-07 01:15:17

标签: c++ c alignment type-conversion casting

我想在C和C ++中将任何类型的指针转​​换为 int 。 C和C ++的代码必须相同。以下程序适用于C但不适用于C ++。

int main(void)
{
    long long a;
    int b = (int)&a;

    return 0;
}

如何让它适用于C ++?

2 个答案:

答案 0 :(得分:6)

看起来你想要offsetof宏,它在<stddef.h>中定义。

修改:您已更改了示例,现在应该查看intptr_t中的uintptr_tstdint.h。在任何情况下,都不要将地址放入普通int

答案 1 :(得分:0)

你的意思是:

struct X
{
        char a;
        long long b;
};

int main(void)
{
        int b[20];
        // C++ requires fixed size of arrays.

        b[(int)(&((struct X*)0)->b) - 8] = 5;
        // This will compile But what you get is not even worth guessing at.

        return 0;
}
相关问题