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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4812731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:37:31  来源:igfitidea点击:

How to get memory address in C and output it?

cpointersbit-manipulation

提问by Buckeye

I need to get memory address and bits of index then I need to output index of the memory address. Can anyone help?

我需要获取内存地址和索引位,然后我需要输出内存地址的索引。任何人都可以帮忙吗?

回答by templatetypedef

Given any variable in C, you can get its address using the "address-of" operator &:

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

int x;
int* addressOfX = &x;

You can print out addresses using the %pspecifier in printf:

您可以使用%pin 中的说明符打印出地址printf

printf("%p\n", &x); // Print address of x

To access individual bits of an integer value, you can use the bitwise shifting operators, along with bitwise AND, to shift the bit you want to the proper position and then to mask out the other bits. For example, to get the 5th bit of x, you can write

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

int x;
int fifthBit = (x >> 4) & 0x1;

This shifts down the number 4 bits, leaving the fifth bit in the LSB spot. ANDing this value with 1 (which has a 1 bit in the lowest spot and 0 bits everywhere else) masks out the other bits and returns the value. For example:

这会将数字向下移动 4 位,将第五位留在 LSB 位置。将此值与 1(最低位为 1 位,其他位置为 0 位)进行 AND 运算,屏蔽掉其他位并返回该值。例如:

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

回答by Buckeye

This worked for me ;)

这对我有用;)

  // uses :: head
  // ----------------------------------------------
     #include <stdio.h>
  // ----------------------------------------------


  // func :: main
  // ----------------------------------------------
     int main()
     {
        void *fooz = "bar";
        char addr[64];

        sprintf(addr, "%p", &fooz);

        // do some stuff with `addr`, or not :)
        puts(addr);

        return 0;
     }
  // ----------------------------------------------

Prints out something like: ~> 0x7ffdfb91d698

打印出如下内容:~> 0x7ffdfb91d698