字符串长度与数组长度不同?

String length not the same as array length?

以下文字显示在 "C in a Nutshell (2nd Edition)."

的第 135 页
#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)

在上面的例子中,我认为 "chop suey"'c', 'h', 'o', 'p', ' ', 's', 'u', 'e', 'y', '[=12=]' 是一样的。这是数组中的 10 个元素。

我的问题是:为什么 "array length" 与本例中的 "String length" 不同? 11 的长度从何而来?导致此问题的 wchar_t 类型有什么特别之处吗?

这看起来像是一个差一错误。很有可能是有人记错了字符。

chop suey是9个字符(也就是字符串的长度);该数组的大小为 10,因为它需要存储标记字符串结尾的 NUL 终止符。

正确答案如下

#include <stdio.h>
#include <wchar.h>

int main(void) 
{
    wchar_t dinner[] = L"chop suey";

    printf( "sizeof( wchar_t ) = %zu\n", sizeof( wchar_t ) );
    printf( "wcslen( dinner ) = %zu, sizeof( dinner ) = %zu\n", wcslen( dinner ), sizeof( dinner ) );

    return 0;
}

程序输出为

sizeof( wchar_t ) = 4
wcslen( dinner ) = 9, sizeof( dinner ) = 40

您可以 运行 使用编译器自己编写程序。

函数wcslen 计算wchar_t 符号的数量,直到遇到终止零。运算符 sizeof returns 数组占用的字节数(包括终止零) dinner.

实际上字符串长度为9,即终止零不计入字符串长度。数组中有 10 个类型为 wchar_t 的符号。

类型的定义 wchar_t 是实现定义的。