计数器方式
注释一
#undef NDEBUG使用断言
#define NDEBUG关闭断言
assert(exp); exp为真,程序继续执行。否则,程序终止。
注释二
str表示首个字符的地址,解引用后为首元素
#include<stdio.h>
#include<assert.h>
int my_strlen(const char* str)
{
int count = 0;
assert(str);
while (*str)
{
count++;
str++;
}
return count;
}
int main()
{
int ret = my_strlen("hello world");
printf("%d", ret);
}
不能创建临时变量计数器
注释
使用递归,大事化小
#include<stdio.h>
#include<assert.h>
int my_strlen(const char* str)
{
assert(str);
if (*str == '\0')
return 0;
else
return 1 + my_strlen(str + 1);
}
int main()
{
int ret = my_strlen("hello world");
printf("%d", ret);
}
指针-指针方式
注释
指针-指针,两指针须是同类型的。
运算的值是两个指针在内存中的距离(该距离以间隔的单元格数为单位,而不是以字节为单位)。
#include<stdio.h>
#include<assert.h>
int my_strlen(char* s)
{
assert(s);
char* p = s;
while (*p != '\0')
p++;
return p - s;
}
int main()
{
int ret = my_strlen("hello world");
printf("%d", ret);
}