问题来源于一道很小的编程题,要求写出strlen的函数。
很来很容易
str为字符指针
int cnt=0;
while(*str != '\0')
cnt++;
return cnt;
在vs2008上顺利执行,但是在题目系统中出问题
题目给的要求是
1000ms 10000K
那就是这种算法超时了,
想想算距离,除了这种计数方法,还有什么
还有就是两绝对地址相减,地址相减得到绝对值差/类型长度
所以修改代码为如下
char* base=str;
while(*str++);
return (str - base -1);
直接找到字符串的结束地址,然后首尾相减。
这种算法相对于前一种,少执行一个计数累加,并且随着字符串长度的增加,效果越好。
编译提交后,符合时间要求。
基于此,要研究一下GNU libc是怎么写这个函数的
不看不知道 一看吓一跳 先贴出源码吧
/* Copyright (C) 1991-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Written by Torbjorn Granlund (tege@sics.se),
with help from Dan Sahlin (dan@sics.se);
commentary by Jim Blandy (jimb@ai.mit.edu).
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */