Explicit cast in C [closed]
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;
}
精彩评论