ProgrammingVery hard
Which statement about finding the length of a null-terminated C string is correct?
- A. strlen is O(1) because the length is stored before the characters
- B. strlen returns at once because the terminator sits at a fixed offset
- C. strlen is O(1) after the first call because the result is cached
- 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
- Which code gives the correct sum of the first n squares, for n up to 10^6, using a closed form in O(1)?
- Which operation on a dynamic array of n elements has O(1) amortised cost when using doubling?
- A loop does for (i = n; i > 0; i /= 2) for (j = 0; j < i; j++) work();. For n = 1024, how many times is work() called in total?
- Which of these is an O(n) method to test whether a string of length n is a palindrome in C?
- char s[] = "hello world"; char w = strchr(s, ' ') + 1; printf("%s", w); What is printed?
- char a[8] = "abc"; memset(a + 1, 'z', 2); printf("%s", a); What is printed?