Search code examples
carrayscharstring-lengthwidechar

String length not the same as array length?


The following text is displayed on page 135 of "C in a Nutshell (2nd Edition)."

#include <stddef.h>              // Definition of the type wchar_t
/* ... */
wchar_t dinner[] = L"chop suey"; // String length: 10;
                                 // array length: 11;
                                 // array size: 11 * sizeof(wchar_t)

In the above example, I would think "chop suey" is the same as 'c', 'h', 'o', 'p', ' ', 's', 'u', 'e', 'y', '\0'. That's 10 elements in the array.

My question is: Why is the "array length" different from the "String length" in this example? Where is this length of 11 coming from? Is there something special about the wchar_t type that is causing this?


Solution

  • That looks like an off-by-one error. Most likely someone just miscounted the characters.

    chop suey is 9 characters (that's the length of the string); the array has size 10 because it needs to store the NUL terminator that marks the end of the string.