2015-10-09 158 views
-3

我看到有人发布这个函数,它返回一个字符串的长度。有人可以逐行向我解释发生了什么,因为我没有看到* s指针发生了什么,以及它如何能够逐个遍历字符串并计算字符串中的字符数量。此功能是在FreeBSD返回一个字符串的长度

size_t 
strlen(const char *str) 
{ 
const char *s; 
for (s = str; *s; ++s); 
return(s - str); 
} 
+1

这不是网站“按行解释代码给我行”。 –

+2

你对C中的指针,指针算术和逻辑条件了解多少? – birryree

+0

我主要知道发生了什么事。只是混淆了什么* s;是在做。 Geeze。我认为对于少量代码来说这不是什么大问题。对于那个很抱歉。 –

回答

2
size_t 
strlen(const char *str) 
{ 
const char *s; // init pointer 
for (s = str; *s; ++s); // set pointer to beginning of str, and increment pointer until 
         // you reach '\0', which is the end of the string 
return(s - str); // compute the distance between end and beginning of string 
       // (s points to end of string, str points to beginning of string) 
} 
+2

而'* s'作为'for'循环中的第二个表达式,是一个隐式评估,测试* *是否指向字符串终结符''\ 0''。在满足''\ 0''之前,任何非0值都为真,即循环继续。 –

+0

谢谢。为解释。我从来没有真正关注过C中隐含的评估 –

+0

@re.m7,有些人明确地使用'true'和'false'的定义。但是,该语言的作品是,任何表达式评估为'0'在逻辑上是错误的,当隐式使用时任何其他情况都是正确的,例如'if(apples)'不需要指定你有多少(或欠);是真的。 –

相关问题