问题描述
我只是在学习 C 并开始了解指针。我的理解是,当您声明一个数组时,该数组的地址是该数组中第一个元素的地址。所有其他元素都连续存储在内存中。
当我使用 online C compiler at 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 %p\n",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、...604 等等。