【问题标题】:Why do address pointers to integers have 8 symbols, and integer binary address locations have 8 bits?为什么指向整数的地址指针有 8 个符号,而整数二进制地址位置有 8 位?
【发布时间】:2014-05-05 19:20:22
【问题描述】:

我写了一段代码(如下所示),将整数0 存储到任意内存位置,然后打印指向该内存位置的指针和该内存位置的二进制地址。

8 位长的二进制内存地址,这是我没想到的。我有 4Gb 的 ram,所以如果整数存储在这个 ram 中,你肯定需要超过 8 位来唯一地寻址这个 ram 中的一个单元(字节)?更令人困惑的是,指针长度为 8 个符号。如果二进制地址是 8 位长,那么指向该地址的指针肯定只需要 2 个符号?

那么为什么地址指针有8个符号,而整数二进制地址位置有8位呢?

我从SE Question 中获取了 byte_to_binary 函数。我还是个初学者,所以我的代码可能不正确。

#include "stdafx.h"
#include <stdio.h>
#include <string.h>     /* strcat */
#include <stdlib.h>     /* strtol */


const char *byte_to_binary(int x)  //code taken from-https://stackoverflow.com/questions/111928/is-there-a-printf-converter-to-print-in-binary-format
{
    static char b[9];
    b[0] = '\0';

    int z;
    for (z = 128; z > 0; z >>= 1)
    {
        strcat(b, ((x & z) == z) ? "1" : "0");
    }

    return b;
}

int main(void) //my code starts here
{
    int A = 0;
    int *Ap = &A;
    unsigned int number = (unsigned int)Ap;

    printf("%s \t %d \n \n","int Value",A); //prints the value stored in Ap as an integer

    printf("%s \t %s \n \n","bin Value",byte_to_binary(A)); //prints the value stored in Ap as a binary number 

    printf("%s \t %p \n \n","adress Pointer",Ap); //prints pointer address as pointer type

    printf("%s \t \t %s \n \n","adress",byte_to_binary(number)); //prints pointer address in binary


    return 0;
}

这个输出:

int Value        0

bin Value        00000000

adress Pointer   003FFE1C

adress           00011100

Press any key to continue . . .

【问题讨论】:

  • 您是如何得出一个地址只有 8 位的结论的?
  • 你应该已经包含了输出。没有它,不清楚你的问题是什么。
  • “当我打印二进制地址时,它只有 8 位长”——那是因为你的循环只运行了 8 次,完全被破坏了。您平台上的指针显然是 32 位的(由带有 %p 格式说明符的 printf 调用的输出证明),因此您需要查看所有 32 位。
  • 最好将输出复制并粘贴为文本,而不是发布控制台窗口的屏幕截图。
  • @Blue7:为什么要以二进制形式打印指针值?十六进制包含相同的信息并且更加简洁。您愿意阅读0xdeadbeef 还是11011110101011011011111011101111?

标签: c pointers memory-address


【解决方案1】:

是你的二进制转换函数不能正常工作。

 0x003FFE1C 

是 00000000001111111111111000011100

你在这些方面做得还不够。

你可能想做一个

 sizeof (Ap) 

看看你需要多少位。 (这里是 32)

您应该更改循环索引,使其成为位位置而不是移位值,否则您有溢出的风险。

for (int ii = 31 ; ii >= 0 ; -- ii)
{

   if (x & (1 << ii) != 0)
      strcat (b, "1) ;
   else
      strcat (b, "0") ;
}

【讨论】:

  • 这让所有的乐趣都消失了 :-)
  • 感谢您的回答!不知道我怎么没发现这个。
猜你喜欢
  • 1970-01-01
  • 2019-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-29
  • 2021-06-28
  • 2014-10-03
相关资源
最近更新 更多