开发者

Explicit cast in C [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago.

I want to convert pointers of any type to int in C and C++. The code must be the same for both C a开发者_如何学Pythonnd C++. The following program works for C but not for C++.

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

    return 0;
}

How can I get it working for C++?


Looks like you want the offsetof macro, it's defined in <stddef.h>.

Edit: You have changed your example, now you should look at intptr_t or uintptr_t which are in stdint.h. Do not, under any circumstances, put an address into a plain int.


Did you mean:

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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜