如何在C中获取内存地址并输出?

Buc*_*eye 3 c pointers bit-manipulation

我需要获取内存地址和索引位然后我需要输出内存地址的索引.有人可以帮忙吗?

tem*_*def 16

给定C中的任何变量,您可以使用"address-of"运算符获取其地址&:

int x;
int* addressOfX = &x;
Run Code Online (Sandbox Code Playgroud)

您可以使用以下%p说明符打印出地址printf:

printf("%p\n", &x); // Print address of x
Run Code Online (Sandbox Code Playgroud)

要访问整数值的各个位,可以使用按位移位运算符和按位AND,将所需的位移位到正确的位置,然后屏蔽掉其他位.例如,要获得第5位x,您可以编写

int x;
int fifthBit = (x >> 4) & 0x1;
Run Code Online (Sandbox Code Playgroud)

这将数字4位向下移位,将第五位留在LSB点.将该值与1(最低点中的1位和其他位置的0位)进行AND运算可以屏蔽掉其他位并返回该值.例如:

int x = 31; // 11111
prtinf("%d\n", (x >> 4) & 0x1); // Prints 1
Run Code Online (Sandbox Code Playgroud)

  • +1比"阅读指针"更有帮助,无论是否可靠. (2认同)