我读到数组桶值存储在连续的内存位置。我试图在我的 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/