为什么C数组元素(看似)存储在块4?



我正在学习C语言,并对指针有所了解。我的理解是,当你声明一个数组时,数组的地址是该数组中第一个元素的地址。所有其他元素都连续存储在内存中。

当我使用在线C编译器在onlinegdb.com运行这段代码时…

int main()
{
int num[5] = { 0, 1, 2, 3, 4 };
for (i = 0; i < 5; i++) {
printf("num[%d] has the value %d and is stored at address %pn",
i, num[i], &num[i]);
}
return 0;
}

我观察到以下情况…

num[0] has the value 0 and is stored at address 0x7ffe9973e600
num[1] has the value 1 and is stored at address 0x7ffe9973e604
num[2] has the value 2 and is stored at address 0x7ffe9973e608
num[3] has the value 3 and is stored at address 0x7ffe9973e60c
num[4] has the value 4 and is stored at address 0x7ffe9973e610

所以从我所看到的,C编译器为num[0]选择了一个内存位置,然后每个后续元素都被放置在四个地址之外。我知道,每个编译器可能是不同的,有不同的行为,但在这种情况下,这是标准的-为什么数组元素似乎存储在四个块?为什么地址模式不是0x7ffe9973e600,...601,...602,...603,...604?每个元素占用多个地址吗?

内存中的地址代表1字节的数据。num数组是int类型的,每个占用4字节。因此,为了存储一个元素num[0],我们需要占用4个字节的内存,因为每个字节需要1个内存地址,因此它们有4个内存地址的缺口。如果它是一个char数组,那么您将看到序列0x7ffe9973e600,…601年,…602年,…603年,…

最新更新