【问题标题】:Internal Array Element Location Algorithm内部数组元素定位算法
【发布时间】:2019-11-20 21:10:51
【问题描述】:

我试图理解 C 中的几个概念,其中之一就是数组。嗯,书里有关于内部数组元素定位算法的解释。

数组中的每个元素都是通过在数组的起始地址上添加一个偏移量来到达的

– 地址元素 i = 起始数组地址 + 偏移量

对于一维数组:

– 偏移量 = i * 单个元素的大小

然而,

#include <stdio.h>
#define  NUMELS 20
int main() {
int numbers[NUMELS];

printf("The starting address of the numbers array is: %d\n", &(numbers[0]));
printf("The storage size of each array element is: %d\n", sizeof(int));
printf("The starting address of the numbers[5] array is: %d\n", &(numbers[5]));
return 0;
}

当这段代码在ma​​cos上执行时,结果是:

The starting address of the numbers array is: -346695536
The storage size of each array element is: 4
The starting address of the numbers[5] array is: -346695516

另一方面,当这段代码在windows上执行时,结果是:

The starting address of the numbers array is: 16514000
The storage size of each array element is: 4
The starting address of the numbers[5] array is: 16514020

我的问题是关于在内存中定位数组。为什么windows使用无符号数,而mac使用有符号数?

编辑:顺便说一句,我已经在同一个 ide 上执行了这些代码。 (克莱恩)。我知道我应该使用 %p 格式说明符,但在书中,它使用的是 %d 格式说明符。所以我只是想知道结果不同的原因。感谢回复!

【问题讨论】:

  • 一切都以二进制形式存储。这就是你解释价值观的方式。您正在使用已签名的%d。请改用%p
  • Mac 上的地址非常高,当它们被解释为有符号数字时,它们会环绕为负数。
  • @Barmar 谢谢。这就是我正在寻找的答案。

标签: c arrays algorithm memory memory-management


【解决方案1】:

程序的内部存储器布局特定于每个实现。在由两个不同编译器生成的程序中,变量的地址很少相同。事实上,它们甚至可以在同一程序的多次运行中有所不同。

另外,在打印指针时,您应该使用%p 格式说明符。您还应该将使用%p 打印的任何指针转换为void *,这是此格式说明符的预期类型。这就是您看到地址为负值的部分原因。当您切换到 %p 时,您很可能会看到非负值。

【讨论】:

  • 事实上,我已经在同一个 ide 上执行了这些代码。 (克莱恩)。是的,我知道,我应该使用 %p 但在书中,它使用的是 %d 格式说明符。我只是想知道结果不同的原因。
猜你喜欢
  • 1970-01-01
  • 2018-04-06
  • 1970-01-01
  • 1970-01-01
  • 2019-01-19
  • 1970-01-01
  • 2014-02-25
  • 1970-01-01
  • 2016-02-20
相关资源
最近更新 更多