c - 为什么打印 C 数组显示不连续的地址?

标签 c arrays pointers

我读到数组桶值存储在连续的内存位置。我试图在我的 64 位 mac 上打印字符数组的内存位置 as

char str1[] = "Hell";
    printf("%p:%lu:%c, %p:%lu:%c, %p:%lu:%c, %p:%lu:%c", str1[0], str1[0], str1[0], str1[1], str1[1], str1[1], str1[2], str1[2], str1[2], str1[3], str1[3], str1[3]);

我得到的结果是

0x48:72:H, 0x65:101:e, 0x7fff0000006c:140733193388140:l, 0x7fff0000006c:108:l

考虑到 char 的大小是 1 字节,这对我来说看起来不像是连续的内存地址。如果我学错了,请帮助我理解这一点。

最佳答案

你的 printf 中的参数陈述不正确。

如果你想打印十进制地址,你应该这样写:

char str1[] = "Hell";
printf("%p:%lu:%c, %p:%lu:%c, %p:%lu:%c, %p:%lu:%c\n",
       (void*)&str1[0], (unsigned long)&str1[0], str1[0],
       (void*)&str1[1], (unsigned long)&str1[1], str1[1],
       (void*)&str1[2], (unsigned long)&str1[2], str1[2],
       (void*)&str1[3], (unsigned long)&str1[3], str1[3]);

但是请注意,将指针转换为 unsigned long可能会丢失信息,因为大小为 unsigned long可能比 char* 小(它在 Windows 64 位上);

如果您打算以十进制和字符形式输出字符,则格式应为 %d并且代码更改为:

char str1[] = "Hell";
printf("%p:%d:%c, %p:%d:%c, %p:%d:%c, %p:%d:%c\n",
       (void*)&str1[0], str1[0], str1[0],
       (void*)&str1[1], str1[1], str1[1],
       (void*)&str1[2], str1[2], str1[2],
       (void*)&str1[3], str1[3], str1[3]);

关于c - 为什么打印 C 数组显示不连续的地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45131043/

相关文章:

arrays - BASH - 作为数组名称一部分的变量(第 2 部分)

C 结构体和函数指针

c - 从键盘接受 5 个字符串的程序

c - 来自 `strsep` 的字符串标记未打印(段错误)

c++ - 如何捕获 x86 上的数据对齐错误(Sparc 上的 SIGBUS)

c++ - 如何从 std::strings 数组中检索特定元素作为 LPCSTR?

c - 为什么函数指针有用?

c - 无需指定 'lib' 前缀即可在 gcc 中链接静态库

c - 以数字作为变量的字符串,Unix C 问题

c++ - C/C++中的数组大小