1.简单的指针
#include"stdio.h"
int x=6;
int t[2]={5,10};
int s[2][2]={1,2,3,4};
char r[7]={'h','e','l','l','o','!','\0'};
char R[2][4]={{'h','e','l','l'},{'o','!','\0'}};
void main()
{
char *pr;
pr=r;
char *pR;
pR=R[0];
int *px;
px=&x;
int *pt;
pt=t;
int *ps;
ps=s[0];
printf("%s\n%s\n",pr,pR);
printf("%d\n%d\n%d\n",*px,*pt,*ps);
}
输出结果:
注意事项:定义指针时,如果指针指向的是个常数,那么一定要加个取地址符,因为指针指向的是个地址,而不是数,常数本身无默认的地址。一维数组赋值的时候默认第一个数的地址给指针,多维数组的指针地址要自己定义,无默认值。如果输出的是个数,那么必须要把值取出来输出;如果是字符串只需要指明首地址就可以全部输出了。
2.指针的移动
#include"stdio.h"
int x=6;
int t[2]={5,10};
int s[2][2]={1,2,3,4};
char r[7]={'h','e','l','l','o','!','\0'};
char R[2][4]={{'h','e','l','l'},{'o','!','\0'}};
void main()
{
char *pr;
pr=r;
pr++;
char *pR;
pR=R[0];
pR++;
int *px;
px=&x;
px++;
int *pt;
pt=t;
pt++;
int *ps;
ps=s[0];
ps++;
printf("%s\n%s\n",pr,pR);
printf("%d\n%d\n%d\n",*px,*pt,*ps);
}
输出结果:
当我们把px++改成px--后
由此可以得出结论:常数的地址是唯一的,不存在移动的问题,移动输出的值也是错误的。数组的地址随着指针的改变而改变,不要超过数组的极限范围都是可以的。
3.结构体指针
#include
struct str
{
int i;
int j;
};
struct str ss={1,2};
struct str *ptr=&ss;
void main()
{
printf("%d\n%d\n",ptr->i,ptr->j);
}
输出结果:
当用到结构体指针时,首先定义一个变量体,对该变量体赋值,定义结构体指针,把指针指向想要的变量体,就可以取我们想要的值了。