函数递归
程序调用自身的编程技巧称为递归(就是一个函数自己调用自己)
递归的两个必要条件
1、存在限制条件,当满足这个限制条件的时候,递归不再继续。 2、每次递归调用之后越来越接近这个限制条件。
递归常见错误——stack everflow——栈溢出
练习创建函数求字符串长度
#include<stdio.h>
int mystrlen(char* str)//定义函数
{
int count = 0;//count用来计字符串长度
while (*str != '\0')//字符串最后是\0,所以不是\0就count++
{
count++;
str++;//str++后w就是o了
}
return count;//循环后返回count就是字符串长度
}
int main()
{
char arr[] = "word";
int a = mystrlen(arr);//arr是数组,数组传参,这里arr接收的是w的地址
printf("%d\n", a);
return 0;
}
不创建临时变量,求字符串长度(用递归)
#include<stdio.h>
int mystrlen(char* str)//定义函数
{
if (*str != '\0')//如果*str不是\0
{
return 1 + mystrlen(str + 1);//1+就是计算字符串长度,str+1就是数组往后走,原来*str是w的地址,+1后就是o的地址