5

i have a program about 2-D arrays

base adress is 8678

#include<stdio.h>
#include<conio.h>
main()
{
 int arr[3][3]={
                 {83,8,43},
                 {73,45,6},
                 {34,67,9}
                 };
printf("%d ",&arr+1);  //points to 8696
printf("%d ",arr+1);   //points to 8684
return 0;
}  

what is the difference between arr+1 and &arr+1?

4

4 回答 4

9

Well, they're different things. arr decays in most contexts to a pointer to the first element of your array - that means a pointer to the first 3-element row in your 2D array: type int (*)[3]. arr + 1, then, points to the second row in the array.

&arr is the address of the array itself (type int (*)[3][3]), so &arr + 1 points to memory just past the end of the entirety of your 2D array.

You can confirm this behaviour easily by printing differently. Specifically, printing the offsets to the new pointers rather than the values themselves will help clear things up. The output from your program from these print statements:

printf("%ld\n",(intptr_t)(&arr+1) - (intptr_t)arr);
printf("%ld\n",(intptr_t)(arr+1) - (intptr_t)arr);

Will be the decimal offsets to &arr+1 and arr+1 respectively. Here's the output from a test run I just made:

36
12

36 matches up: 3 rows × 3 columns × 4 bytes per entry = 36 bytes. So does the 12: 1 row × 3 columns × 4 bytes per entry = 12 bytes.

Note - you're also printing pointers using %d, which is wrong. You should probably be using %p for that.

于 2012-08-08T04:37:53.880 回答
1

你可以借助这个等价来解决这个问题:X[Y] === *(X+Y)

由于 *(arr+1) === arr[1], arr+1 === &arr[1]

同样, &arr+1 === &((&arr)[1])

什么是 (&arr)[1]?嗯,(&arr)[0] === *&arr === arr,也就是3x3数组本身,所以(&arr)[1]就是后面的3x3数组,&arr+1 === &(( &arr)[1]) 是 &arr 之后的 3x3 数组的地址 ... 一个指向刚刚超过整个数组的字节的指针。

于 2012-08-08T05:39:10.717 回答
0

Arr+1 给出数组中的下一个元素,而 &arr +1 给出下一个整数数组的地址

于 2017-08-15T12:06:24.137 回答
-1

array + 1 表示 array[1] 的地址,它花费 3 int 内存。

&array + 1 表示array[0]的地址加1;

于 2012-08-08T05:50:33.940 回答