Please explain the difference

坚强是说给别人听的谎言 提交于 2019-12-30 02:26:08

问题


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?


回答1:


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.




回答2:


You can figure this out with the help of this equivalence: X[Y] === *(X+Y)

Since *(arr+1) === arr[1], arr+1 === &arr[1]

Similarly, &arr+1 === &((&arr)[1])

What is (&arr)[1]? Well, (&arr)[0] === *&arr === arr, that is, the 3x3 array itself, so (&arr)[1] is the 3x3 array following that, and &arr+1 === &((&arr)[1]) is the address of the 3x3 array following &arr ... a pointer to the byte just past the entire array.




回答3:


Arr+1 gives the next element in an array while &arr +1 gives the address of next array of integers




回答4:


array + 1 means the array[1] 's address and it costs 3 int memory.

&array + 1 means the address of array[0] add 1;



来源:https://stackoverflow.com/questions/11857698/please-explain-the-difference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!