C Programming Basics
char s[10] = "hello";
printf("%zu %zu\n", strlen(s), sizeof s);Which of the following is the output when the code above, which concerns a char array holding a string, is executed?
- A5 10
- B6 10
- C10 10
Show answer and explanation
Answer: A. 5 10
A string in C is a sequence of characters followed by the terminating character '\0'. strlen counts the characters from the start up to just before '\0', so it gives 5 for "hello". sizeof s is the size of the whole array s, the declared 10 bytes (the remaining elements hold 0). Omitting the number of elements, as in char s[] = "hello"; gives a 6-byte array including '\0'.
- A. Correct. strlen gives 5 without counting the terminating '\0', and sizeof gives the array's 10 bytes.
- B. strlen does not count the terminating '\0', so it is 5, not 6.
- C. strlen returns the number of characters before '\0', not the size of the array.