1

如果我有一个大小为 10 且基地址为 say 的数组0x5600bc。数组和数组的每个元素的内存位置是ptr什么?

例如:Arr[0]地址是什么,会是0x5600bc什么?& 那会Arr[1]0x5600c0吗?

4

3 回答 3

4

给定

typename foo[10] = { 0 };

然后foo[0]将在某个地址,(uintptr_t)&foo[0].

foo[1]位于(uintptr_t)&foo[0] + sizeof typename,并且foo[n]位于(uintptr_t)&foo[0] + n * sizeof typename

像这样(假设这里是 4 字节类型)

0x00000000 arr[0] <- arr is a pointer to this location
0x00000004 arr[1]
0x00000008 arr[2]
...

如果你有一个 32 位整数数组,每个 4 个字节,并且数组从 开始,0x5600bc那么是的,arr[1]将在0x5600c0.

您可以像这样打印数组中每个元素的地址:

#include <stdlib.h>
#include <stdio.h>

int main(void) {
  #define ARR_SIZE 10
  int arr[ARR_SIZE] = {0};

  for (size_t n = 0; n < ARR_SIZE; ++n) {
    printf("arr[%zu] = %p\n", n, (void*)&arr[n]);
  }

  return EXIT_SUCCESS;
}
于 2015-04-29T21:51:43.230 回答
2

的位置Arr[n]将是0x5600bc + n*sizeof(Arr[0])。所以如果数组元素的大小是4Arr[1]确实会在0x5600c0

于 2015-04-29T21:35:42.773 回答
0

数组名(标识符)实际上是指向它的第一个元素的指针,所以答案Arr[0]0x5600bc. 取决于type数组,更具体地说,它的element size(以字节为单位)将确定每个下一个元素的地址的增量。

一般来说,使用间接寻址模式,你有: base address + offset, where base = array name,offset = (element size)*(index of element)

对数组指针和数组的很好的解释。

图示: 在此处输入图像描述

于 2015-04-29T21:35:57.137 回答