指针
(小白总结,仅供参考,如有错误,欢迎讨论)
1.一级指针
1.1源代码
#include<stdlib.h>
int main(int argc,char*argv[])
{
int a=8;
int *p,**h;
p=&a;
h=&p;
printf("%d\n",a);//a的内容
printf("%d\n",&a);//a的地址
printf("%d\n",*p);//p所指向的地方的内容
printf("%d\n",p);//p的内容
printf("%d\n",&p);//p的地址
printf("%d\n",h);//h的内容
printf("%d\n",*h);//h所指向的地方的内容
printf("%d\n",**h);//*h所指向的地方的内容
printf("%d\n",&h);//h的地址
printf("%d\n",&*h);//h所指向的地址的内容(p)的地址
system("pause");
return 0;
}
1.2显示
1.3总结
总之,指针里存放的永远是地址,不管是几级指针都一样。(如:一级指针里装的是非指针地址,二级指针里装的是一级指针的地址,以此类推)
注意:二级指针h代表的是h里的内容,即:以及指针地址;&h代表的是二级指针的地址;*h代表的是h所指向的地方(即一级指针)里的内容;**h代表的是h所指向的地方(即一级指针)里的内容(非指针地址)的地方的内容。(多级指针以此类推)
2.多级指针
2.1源代码
####2.1.1数组指针(行指针)(属于一级指针)、二级指针、三级指针
#include<stdio.h>
int main(int argc,char*argv[])
{
int a[2][3]={{4,7,2},{8,5,1}};
int (*p)[3];//行指针(数组指针)
p=a;//此刻的a代表的是首层楼的地址,单位相同,都是一层楼。p=&a为什么是错的呢?因为单位不同 ,p是一层楼,&a是一栋楼
printf("%d\n",&(*p));//对于指针和数组&相当于升级,*相当于降级
printf("%d\n",&p);//该层楼的地址,该栋楼只有一层
printf("%d\n",p);//一层楼的内容(地址)(去往房间)
printf("%d\n",*p);//首房间内容 (地址)
printf("%d\n",**p);//该地址的内容(4)
printf("%d\n",*((*p)+1));//注意(*p)的单位是一个房间。第二个房间的地址的内容
printf("%d\n",*p+1);
printf("%d\n",(*p)+1);//优先级:()>*>+q。所以加一间房int-->4
printf("%d\n",*(p+1));//单位p一层楼,即加3*4
printf("%d\n",**(p+1));//第二层楼的首房间的内容(地址)的内容(8)
printf("%d\n",**p+1);//第一层楼的首房间的内容的内容(4)+1
printf("%d\n",a);
printf("%d\n",a+1);
printf("%d\n",&a);
printf("%d\n",&a+1);//加一栋楼2*3*4
// printf("%d\n",&(a+1));错误的写法第二层的全部???出错啦!
printf("%d\n",*a);
printf("%d\n",**a);
printf("%d\n",a[0]);
printf("%d\n",a[0][0]);
printf("--------------------------------\n");
//指针数组在示例里
int (**q)[3];
int (***w)[3];
w=&q;
q=&p;
printf("%d\n",&q);//二级指针层地址
printf("%d\n",q);//该层内容,一级指针地址(直接去往该地址)
printf("%d\n",*q);//一级指针内容,数组首层地址
printf("%d\n",**q);//数组首层地址内容,数组首层地址的首房间
printf("%d\n\n",***q);//数组房间内容
printf("%d\n",&w);//三级指针层地址
printf("%d\n",w);//该层内容,二级地址
printf("%d\n",*w);//二级指针层内容,一级地址
printf("%d\n",**w);//一级指针层内容,数组首层地址
printf("%d\n",***w);//数组首层第一间地址
printf("%d\n",****w);//数组首层第一间地址内容(4)
//总结:多级指针间降级直接去到该地址显示内容,而降到最低(数组后,
//还要再降一次到房间,才到降到房间内容) ,降单位先降等级再降楼层最后降房间(降指针级也相当于降房子等级)
printf("----------------------------------\n");
return 0;
}
2.1.2指针数组
#include<stdio.h>
int main(int argc,char*argv[])
{
int a[3]={4,6,2};
printf("%d\n",a);
printf("%d\n",&a);
const char *fruit[3]={"grape","apple","peach"};//指针数组,一级指针
const char **p=NULL;
int i;
p=fruit;//单位相同,都是一个房间 ,二级指针指向一级指针
for(i=0;i<3;i++)
{
printf("%s\n",*p++);
}
const char *msg = "hello";
msg="hi";//特殊规定(hi在静态存储区里待着)(把字符串的首地址赋给msg)
printf( "%s\n",msg);
int b[3]={1,4,2};
int *g;
g=b;//此时的b代表的是首元素的地址,即降一级
printf("%d\n",*g);//地址里的内容
printf("%d\n",g);
return 0;
}