【发布时间】:2021-06-06 06:34:17
【问题描述】:
我只是在学习 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?每个元素是否占用多个地址?
【问题讨论】:
-
因为
int有4个字节? (请注意int有至少 16 位,所以它可能发生在int有2 个字节或8 个字节的不同平台上) -
哦...是的,这是有道理的。谢谢。
-
任何 C 编程书籍的第一章通常都会解决各种整数类型的数值限制,从而确定它们的大小。
-
int数组的每个元素都使用了sizeof(int)可寻址内存位置。 (C 标准将可寻址的内存位置称为“字节”,无论它有多少位。)
标签: arrays c memory memory-address