【发布时间】: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;
}
当这段代码在macos上执行时,结果是:
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