在c语言中,通过指针变量可以直接通过其指向的内存地址来操所其上所存储的变量,结合内存四区,可以很好的完成对代码的理解。
现在先解释非常经典的while(*s++=*t++){}实现的一个字符串拷贝。
#include<stdio.h>
void my_copy1(char *from, char *to)
{
for(;*from!='\0';from++,to++)
{
*to=*from;
}
*to='\0';
}
void my_copy2(const char *from, char *to)
{
if(from==NULL)
return ;//为保证代码健壮性
char *tmpfrom,*tmpto;//利用辅助指针变量来接形参,防止对形参产生影响
//后续省略
tmpfrom=from;
tmpto=to;
while(*tmpfrom!='\0')
{
*tmpto=*tmpfrom;
tmpto++;
tmpfrom++;
}
*tmpto='\0';//此时指针变量tmpto指向字符串最后一个
//字母的下一位置,应手动补'\0'
}
void my_copy3(const char *from, char *to)
{
if(from==NULL)
return ;
while((*to=*from)!='\0')//此行给*to赋值 并判断是否到了字符串尾
{
from++;
to++;
}
*to='\0';
}
void my_copy4(const char *from, char *to)
{
if(from==NULL)
return ;
while((*to++=*from++)!='\0')//将指针后移在此实现
{
}
*to='\0';
}
void my_copy5(const char *from, char *to)
{
if(from==NULL)
return ;
while((*to++=*from++))//判断为真,省略!='\0' 至此结束
{
}
*to='\0';
}
void main()
{
char str1[]="abcdefg";
char str2[100];
//my_copy1(str1,str2);
//my_copy2(str1,str2);
// my_copy3(str1,str2);
// my_copy4(str1,str2);
my_copy5(str1,str2);
printf("str1 : %s\n",str1);
printf("str2 : %s\n",str2);
}
这段代码涉及一维数组做函数参数的退化问题,即形参应退化为该数组的首元素地址,故形参用一个指针变量去接。上述代码一步步的推导了while(*s++=*t++){}这一实现的到处,此段代码在我刚学习c指针时候极大的勾起我的兴趣,故分享。当然其中还涉及操作符运算顺序的问题。
此外 指针数组和指向二维数组的数组指针在此还未涉及,将在以后的博客中分享。
下面是一段简单的函数指针代码。函数指针和返回值为指针的函数有着本质区别,返回值为指针的函数只是返回值的类型是指针变量,其余与普通函数无异。
#include <stdio.h>
int my_swap(int *x,int *y)
{
if(x==NULL||y==NULL)
{
return -1;
}
int temp;
temp=*x;
*x=*y;
*y=temp;
return 0;
}
void main()
{
int a=10;
int b=20;
//my_swap(&a,&b);
int (*fun_p)(int *a,int *b)=NULL;//定义一个函数指针fun_p;
fun_p=my_swap;//让fun_p指向函数的入口地址
fun_p(&a,&b);
printf("a:%d\n",a);
printf("b:%d\n",b);
printf("hello\n");
}
上述函数通过指针做函数参数实现两个整形变量的交换。每一个函数都有自己的入口地址, int (*fun_p)(int *a,int *b)=NULL初始化一个指向函数的指针变量,此外,也可通过typedef定义 :
typedef int(MyFuntype)(int a,int b);
MyFuntype *fun_p=NULL;
fun_p=my_swap 让此函数指针指向需要调用的函数,调用方法为指针变量名字加上形参列表。