访问数组元素

时间:2013-10-20 07:51:28

标签: c arrays pointers

int arr[]= {5,15,1,3,4};

    // Since we know arr and &arr are both address of first element of array.
    // I read somewhere that &arr+1 = baseaddress + sizeof(arr).
    // arr+1 = address of second element
    // am curious to know the diff. between two semantics.
printf("%d %d\n",*(arr+1), *(&arr+1));

我知道这很简单,但我很想清除这个概念。

4 个答案:

答案 0 :(得分:2)

arr的类型为array,&arr的类型为pointer(array)。他们的类型不一样。

这个&arr+1是指针算术。将&arr增加1将使您在数组中的最后位置+ 1。例如:

   |0|1|2|3|4| |
 arr^         ^
        &arr+1^

答案 1 :(得分:2)

arr的类型为int[4],它会衰减到表达式arr + 1中第一个元素的地址,向arr中的第二个元素添加一个结果点;而&arr的类型为int(*)[4],并向&arr添加一个,使其指向实际上不存在的下一个数组,从而在运行时解除引用*(&arr+1)未定义的行为。考虑下面的图表:

              +---------------+
              |       5       | --+   arr[0]
              |---------------|   |
 arr + 1 ---> |       15      |   |   arr[1]
              +---------------+   |
              |       1       |   |   arr[2]
              +---------------+   |
              |       3       |   |   arr[3]
              +---------------+   |
              |       4       | --+   arr[4]
              +---------------+
              |   Random      |
&arr + 1 ---->|   Memory      |
              +---------------+
              |               |
              +---------------+

*(arr+1)取消引用arr的第二个元素,*(&arr+1)取消引用随机内存

答案 2 :(得分:1)

arr是数组而不是第一个元素的地址。它衰减到指向数组arr的第一个元素。 &arr是包含数组arr的整个内存块的地址 在

printf("%d %d\n",*(arr+1), *(&arr+1));

*(arr+1)取消引用数组arr的第二个元素(你会得到15但是会​​调用未定义的行为,因此这里没有任何说法) *(&arr+1)将调用未定义的行为。这是因为您要取消引用数组arr之外的整个数组块(在已分配的内存之外)。

答案 3 :(得分:1)

#include <stdio.h>

int main() {
  int arr[5] = {5,15,1,3,4}; //arr is an array of 5 ints

  //arrays are just pointers to their first value
  printf("the value of arr: %p\n", arr); 
  //this should be the same as arr, since arr is just a pointer to its first value
  printf("the locate of arr[0]: %p\n", &arr[0]);

  //arr+1 is just pointer arithmetic. So arr+1 should be a pointer to the second element in arr.
  printf("When we dereference the pointer to the second element in arr, we should get that number: %d\n", *(arr+1));

  //Since arr is a pointer to the first element in an array, address-of'ing it gives us the address of that pointer in memory.
  printf("*(&arr+1): %p\n", *(&arr+1));
  //Adding 1 to the address of a pointer just gives us a higher address that points to nothing in particular (some place on the stack)
}

/*
 * Output:
 * the value of arr: 0x7ffff2681820
 * the locate of arr[0]: 0x7ffff2681820
 * When we dereference the pointer to the second element in arr, we should get that number: 15
 * *(&arr+1): 0x7ffff2681834
 */

编辑:   通过为其他4个内存地址添加打印,我们可以看到*(&amp; addr + 1)指向数组中第五个元素之后的位置。

 arr+1: 0x7fff38560224

 arr+2: 0x7fff38560228

 arr+3: 0x7fff3856022c

 arr+4: 0x7fff38560230