c - C语言中的指针是如何组成的?

标签 c pointers

我想在 printf 中创建与 %p 标记等效的内容并写入指针的十六进制值。但我想知道 0x 和前 4 个字符是什么意思?因为当我将其从十进制转换为十六进制时,我只有最后 8 个字符。 那么构成指针的三个部分是什么呢?

我的意思是:当我尝试将指针转换为十六进制时(使用我自己的函数),我得到 8 个字符。

当我使用 printf 的 %p 标志时,我得到如下所示的返回:[0x][7ffd][我得到的最后 8 个字符](不带 [])

这是我的转换代码(它只适用于十六进制、二进制和八进制):

char    *convert_to_base(int nb, char *base_str)
{
  char  *result;
  int   i;
  int   has_begin;
  int   base;
  int   diviser;

  base = my_strlen(base_str);
  result = malloc(sizeof(char) * 12);
  diviser = (base >= 10) ? my_power_rec(base, 7) : my_power_rec(base, 10);
  has_begin = 0;
  i = 0;
  while (diviser != 0)
    {
      if (!has_begin)
        has_begin = (base_str[nb / diviser] != '0') ? 1 : 0;
      if (has_begin)
        {
          result[i] = base_str[nb / diviser];
          nb =  nb % diviser;
          i += 1;
        }
      diviser /= base;
    }
  result[i] = '\0';
  return (result);
}

我使用openSUSE

最佳答案

根据p说明符的标准规范,

The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.

也就是说,在某些平台(例如 Linux)中,出于 printf 的目的,指针可能被视为 unsigned long。因此,您看到的是以 16 为基数转换的整数指针值。

在不了解您的平台的情况下,只能说这么多。

关于c - C语言中的指针是如何组成的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40592293/

相关文章:

c - 多个返回语句在 C 中如何工作?

c++ - 当(错误地)取消对指针的引用时,我如何收到以下输出?

c - 为什么不能将指针分配给数组?

c - 使用 "Pointer to a function"调用函数背后的逻辑

c++ - sizeof(Structure) 困惑

python - 将 python 库绑定(bind)到 C

c - 在 C 中使用 strtok() 的段错误

c# - 将二进制读取函数从 C# 转换为 C

c - 'jpg_name' 可以在此函数中使用未初始化的 [-Werror=uninitialized]

c++指向动态矩阵中行的指针