文章目录
- No1
- No2
- No3
- No4
- No5
- No6
一定要理解跨度
No1
#include <iostream>
using namespace std;
int main() {
int a[]={1,2,3,4,5};
//&a+1是整个数组的一个跨度(无论a是多少维数组)
int *p = (int*)(&a+1);
cout<< *(a+1) <<endl;//2
cout<< *(p-1) <<endl;//5
}
No2
#include <iostream>
using namespace std;
int main() {
int a[2][2][3]={{{1,2,3},{4,5,6}},{{7,8,9},{10,11,12}}};
//跨度整个数组
int *p = (int*)(&a+1);
//跨度是[2][2][3]除去第一个,也就是6int
cout<< *(int*)(a+1) <<endl;//7
//跨度是[2][2][3]除去前两个,也就是3int
cout<< *(int*)(*a+1) <<endl;//4
//跨度是[2][2][3]除去前三个,也就是1int
cout<< *(int*)(**a+1) <<endl;//2
cout<< *(p-1) <<endl;//12
}
No3
#include <iostream>
using namespace std;
int main() {
static const char*s[]={"black","white","pink",
"violet"};
const char** ptr[]={s+3,s+2,s+1,s},***p;
p=ptr;
++p;
cout<< **p+1 <<endl;//ink 输出的是一个字符及其之后的内容
return 0;
}
No4
#include <iostream>
using namespace std;
int main() {
int a[3][4]={{1,2,3,4},
{2,3,4,5},
{3,4,5,6}};
int b[3][4]={{10,11,12,13},
{11,12,13,14},
{12,13,14,15}};
int (*aa[2])[4]={a,b};//*aa[2] == aa[2][3]
int *p1[3]={a[0],a[1],a[2]};
int *p2[3]={b[0],b[1],b[2]};
int **pp[2]={p1,p2};
int ***p=pp;//p[2][3][4]
cout<< (*(*p+2))[1] <<endl;//4 a[2][1]
cout<< aa[1][2]-aa[1][0] <<endl;//8
return 0;
}
No5
#include <iostream>
using namespace std;
int main() {
const char* str[]={"Welcome","to","Beautiful","nanjing"};
const char **p = str+1;
str[0]=(*p++)+2;//后置++,先使用*p,后p++
str[1]=*(p+1);
str[2]=p[1]+3;
str[3]=p[0]+(str[2]-str[1]);
cout<< str[0] <<endl;//空字符
cout<< str[1] <<endl;//nanjing
cout<< str[2] <<endl;//jing
cout<< str[3] <<endl;//g
return 0;
}
No6
#include <iostream>
using namespace std;
int main() {
const char* str[]={"Welcome","to","Beautiful","nanjing"};
const char **cp[]={str+3,str+2,str+1,str};
const char*** cpp = cp;
cout<< **++cpp <<endl;//Beautiful
cout<< *--*++cpp+3 <<endl;//come
cout<< *cpp[-2]+3 <<endl;//jing
cout<< cpp[-1][-1]+1 <<endl;//o
return 0;
}