指针函数
视频锁定
{$ currentTime | date:'mm:ss' $}
{$ timeLeft | date:'mm:ss' $}
在前面的学习中我们知道函数的类型和函数的返回值类型是一致的,那指针函数是不是返回值是指针类型的呢?非常正确。指针函数就是函数类型和返回值都是指针的函数,指针函数的一般形式: 类型 * 函数名(参数列表)
下面我们就使用指针函数来实现一个截取子字符串的函数:
#include <stdio.h>
/*截取子字符串的指针函数substring*/
char * substring(char s[],int,int);
int main()
{
char string[] = "i Love C Language!";
char *ps=NULL;
ps = substring(string,2,7);
//string是被截取的字符串,2是开始位置,7是结束位置
printf("%s\n",ps);
return 0;
}
char * substring(char s[],int i,int j)
{
static char temp[100];
/*这个地方声明的临时数组必须是static的,否则值传不回去*/
int n,m;
for(m=0,n = i;n<=j;n++,m++)
{
temp[m] = s[n];
}
temp[m]='\0';
return temp;
}
运行上面的函数体会一下函数的返回值为指针的奇妙吧。
接下来你来想想如果temp数组不声明为static
的话,有没有别的方法可以也实现这个功能呢?
在线练习
{$ activeFileHint $}