开发者

understanding strlen function in C

开发者 https://www.devze.com 2023-01-17 07:03 出处:网络
I am learning C. And, I see this function find length of a string. size_t strlen(const char *str) { siz开发者_高级运维e_t len = 0U;

I am learning C. And, I see this function find length of a string.

size_t strlen(const char *str) 
{ 
 siz开发者_高级运维e_t len = 0U; 
 while(*(str++)) ++len; return len; 
}

Now, when does the loop exit? I am confused, since str++, always increases the pointer.


while(*(str++)) ++len;

is same as:

while(*str) {
 ++len;
 ++str;
}

is same as:

while(*str != '\0') {
 ++len;
 ++str;
}

So now you see when str points to the null char at the end of the string, the test condition fails and you stop looping.


  1. C strings are terminated by the NUL character which has the value of 0
  2. 0 is false in C and anything else is true.

So we keep incrementing the pointer into the string and the length until we find a NUL and then return.


You need to understand two notions to grab the idea of the function :

1°) A C string is an array of characters.

2°) In C, an array variable is actually a pointer to the first case of the table.

So what strlen does ? It uses pointer arithmetics to parse the table (++ on a pointer means : next case), till it gets to the end signal ("\0").


Once *(str++) returns 0, the loop exits. This will happen when str points to the last character of the string (because strings in C are 0 terminated).


Correct, str++ increases the counter and returns the previous value. The asterisk (*) dereferences the pointer, i.e. it gives you the character value.

C strings end with a zero byte. The while loop exits when the conditional is no longer true, which means when it is zero.

So the while loop runs until it encounters a zero byte in the string.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号