A
A
Anarbek Balmukanov2015-06-04 18:34:55
C++ / C#
Anarbek Balmukanov, 2015-06-04 18:34:55

How are the two implementations of strlen() different?

I saw this implementation of strlen:

size_t strlen(char *str) {
  return (char*)memchr(str, '\0', -1) - str;
}

But this implementation does not produce correct values. Wrote myself:
size_t strlen(char *str) {
  int count = 0;
  while(str[count] != '\0'){
    ++count;
  }
  return count - 1;

Why is my implementation bad and why doesn't the first one work?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jcmvbkbc, 2015-06-05
@jcmvbkbc

But this implementation does not produce correct values.

And it should. What does she give out?

D
Dvvarreyn, 2015-06-08
@Dvvarreyn

The concept of length is different.
If the result is to index the string, then in the first case we get the first encountered '\0', and in the second - the element before the first '\0'.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question