Please explain the difference

后端 未结 4 663
攒了一身酷
攒了一身酷 2020-12-30 15:33

i have a program about 2-D arrays

base adress is 8678

#include
#include
         


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-30 15:40

    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.

提交回复
热议问题