指针运算
#include<stdio.h>
int main(void)
{
int urn[5]={100,200,300,400,500};
int *ptr1,*ptr2,*ptr3;
ptr1=urn;
ptr2=&urn[2];
printf("ptr1=%p,*ptr1=%d,&ptr1=%p\n",ptr1,*ptr1,&ptr1);
//指针加法
ptr3=ptr1+4;
printf("ptr1+4=%p,*(ptr1+3)=%d\n",ptr1+4,*(ptr1+3));
ptr1++; //递增
printf("ptr1=%p,*ptr1=%d,&ptr1=%p\n",ptr1,*ptr1,&ptr1);
ptr2--; //递减
printf("ptr2=%p,*ptr2=%d,&ptr2=%p\n",ptr2,*ptr2,&ptr2);
--ptr1;
++ptr2;
printf("ptr2=%p,ptr1=%p,ptr2-ptr1=%d\n",ptr2,ptr1,ptr2-ptr1);//指针减另一个指针
printf("ptr3=%p,ptr3-2=%p\n",ptr3,ptr3-2);
return 0;
}
求差值:两个指针间的差值,通常对分别指向同一个数组内的两个元素的指针求差值,以求出元素之间的距离,差值单位是相应类型的大小。
指针与二维数组
#include<stdio.h>
int main(void)
{
int zippo[4][2]={{2,4},{6,8},{1,3},{5,7}};
printf("zippo=%p,zippo+1=%p\n",zippo,zippo+1);
printf("zippo[0]=%p,zippo[0]+1=%p\n",zippo[0],zippo[0]+1);
printf("*zippo=%p,*zippo+1=%p\n",*zippo,*zippo+1);
printf("zippo[0][0]=%d\n",zippo[0][0]);
printf(" *zippo[0]=%d\n",*zippo[0]);
printf("**zippo=%d\n",**zippo);
printf("zippo[2][1]=%d\n",zippo[2][1]);
printf("*(*(zippo+2)+1)=%d\n",*(*(zippo+2)+1));
return 0;
}
// zippo[m][n]==*(*(zippo+m)+n)
分配内存 malloc()和free()
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
double * ptd;
int max;
int number;
int i=0;
scanf("%d",&max);
ptd=(double *)malloc(max*sizeof(double));
if(ptd==NULL)
{
puts("memory allocation failed");
exit(EXIT_FAILURE);
}
while(i<max&&scanf("%lf",&ptd[i])==1)
++i;
printf("%d\n",number=i);
for(i=0;i<number;i++)
{
printf("%7.2f ",ptd[i]);
if(i%7==6)
putchar('\n');
}
if(i%7!=0)
putchar('\n');
puts("Done");
free(ptd);
return 0;
}