ProgrammingVery hard

Which statement about finding the length of a null-terminated C string is correct?

  1. A. strlen is O(1) because the length is stored before the characters
  2. B. strlen returns at once because the terminator sits at a fixed offset
  3. C. strlen is O(1) after the first call because the result is cached
  4. D. strlen must scan the characters up to the terminator, so it costs O(length)

Correct answer: D. strlen must scan the characters up to the terminator, so it costs O(length)

A C string stores no length field, so strlen reads each byte until it finds the terminator. Reading the first byte with *s is O(1), but that is not the length.

More C Programming questions

Exams that ask this topic