内部数组元素定位算法

问题描述 投票:0回答:1

我试图理解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使用带符号数字?

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

c arrays algorithm memory memory-management
1个回答
1
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.