Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be returned by the following C code?

size_t strlen(const char *s)
{
    const char *sc;
    for (sc = s; *sc != '\0'; ++sc)
        ;
    return (sc - s);
}

  • A.number of characters equal in sc
  • B.length of string s
  • C.doesn’t return any value
  • D.displays string s

Answer: B

Correct answer: length of string s

This is the textbook implementation of strlen. The pointer sc starts at the beginning and advances until it meets the terminating null; the difference sc - s is then the number of characters before it - that is, the length of the string, not counting the null. Pointer subtraction gives a count of elements, which for char is a count of bytes.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.