0
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

4 回答 4

2

的类型arrint[4]衰减到表达式中第一个元素的地址arr + 1,添加一个结果指向第二个元素arr;而 type of &arrisint(*)[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)取消引用随机存储器

于 2013-10-20T08:17:24.253 回答
2

arr是数组类型,&arr是指针(数组)类型。它们的类型不一样。

&arr+1是指针算法。增加&arr1 将使您到达数组中的最后一个位置 + 1。例子:

   |0|1|2|3|4| |
 arr^         ^
        &arr+1^
于 2013-10-20T07:54:32.723 回答
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 个内存地址的打印,我们可以看到 *(&addr+1) 指向数组中第五个元素之后的位置。

 arr+1: 0x7fff38560224

 arr+2: 0x7fff38560228

 arr+3: 0x7fff3856022c

 arr+4: 0x7fff38560230
于 2013-10-20T08:24:49.270 回答
1

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

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

*(arr+1)取消引用数组的第二个元素arr(你会得到15但调用了未定义的行为,所以这里什么都不能说)同时 *(&arr+1)将调用未定义的行为。这是因为您正在取消引用数组之后的整个数组块arr(在分配的内存之外)。

于 2013-10-20T07:54:21.890 回答