自定义strlen()
源代码
/*
* 自定义strlen()函数
*
*/
#include <stdio.h>
#include <assert.h>
#include <string.h>
int my_strlen(const char *str)
{
int count = 0;
assert(NULL != str);
while (*str++ != '\0')
count++;
return count;
}
int main(void)
{
char str[] = "hello world";
char *ptr = NULL;
printf(" strlen(str) : %d\n", (int)strlen(str));
printf("my_strlen(str) : %d\n", my_strlen(str));
printf("my_strlen(ptr) : %d\n", my_strlen(ptr));
return 0;
}
运行结果
[root@localhost lwp_workspace]# ./test
strlen(str) : 11
my_strlen(str) : 11
test: my_strlen.c:14: my_strlen: Assertion `((void *)0) != str' failed.
已放弃
[root@localhost lwp_workspace]#
本文介绍了一个简单的自定义strlen()函数实现方法,并通过源代码示例展示了如何使用该函数来计算字符串长度。同时,文章还提供了一段测试代码及运行结果,用于验证自定义函数的正确性。
1015

被折叠的 条评论
为什么被折叠?



