编译器如何解释&[0] +1和&a + 1计算

Ang*_*gus 2 c

#include<stdio.h>
int main(){
    int a[5] = {0,1,2,3,4};
    int * ptr;
    ptr =(int *) &a;
    printf("\n&a:%u,&a[0]:%u,ptr:%u\n",&a,&a[0],ptr);
    ptr = (int*)(&a+1);
    printf("\n&a:%u,&a[0]:%u,ptr:%u\n",&a,&a[0],ptr);
    ptr = (int*)(&a);
    ptr = (int*)(&a[0]+4);
    printf("\n&a:%u,&a[0]:%u,ptr:%u,*ptr:%d\n",&a,&a[0],ptr,*ptr);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

O/P:

&a:3213284540,&a[0]:3213284540,ptr:3213284540

&a:3213284540,&a[0]:3213284540,ptr:3213284560

&a:3213284540,&a[0]:3213284540,ptr:3213284556,*ptr:4
Run Code Online (Sandbox Code Playgroud)

在上面的代码&a&a[0]给出相同的地址3213284540.但添加的两种情况1给出了不同的地址.

&a[0]+1 => 3213284540 + 4     = 3213284544   [The value stored in this address is '1']
&a+1    => 3213284540 + (5*4) = 3213284560   [Goes Out of bounds of the array] 

&a+1 is equivalent to sizeof(array)+1. 
Run Code Online (Sandbox Code Playgroud)

但是编译器如何解释这个&a[0]+1&a+1

cni*_*tar 7

但编译器如何解释这个&a [0] +1和&a + 1

它是指针算术,所以知道指向的类型和一个基本的东西总是很重要的:添加1到指针使它指向一些"下一个"元素.

  • 在您的示例中&a[0]是类型,int *因此添加1 将指针移动到下一个int.因此地址应增加4/8字节左右,具体取决于sizeof(int)

  • 但是,&a是类型int (*)[5].因此,向它添加1 将指针移动到下一个数组.实际上,地址应该增加sizeof(a).


附注:%p打印指针值时使用.