c中指针地址加1

c、c++中一些指针、数组地址加减的问题

题目1

1
2
3
4
5
6
7
8
9
10
11
12
#include<stdio.h>

int main(){
int a[5]={0,1,2,3,4};
int *p=(int *)(&a+1);
printf("%p\n",&a);
printf("%p\n",&a+1);
printf("%d\n",*(p));
printf("%d\n",*(p-1));
printf("%d\n",*(p-2));
return 0;
}

结果

1
2
3
4
5
0x7ffcfb1f5830
0x7ffcfb1f5844
32764
4
3

指针P+n = 指针P + sizeof(指针的类型) n
sizeof(a)=20 a的类型是int(
)[5]

如果改为int *p=(int *)(&a[0]+1);结果就完全不同了

参考1
参考2

Contents
  1. 1. 题目1
|