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

时间:2019-08-10 14:33:32

标签: c arrays char string-length widechar

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

from tkinter import * #required.
from tkinter import messagebox #for messagebox.

App = Tk() #required.
App.withdraw() #for hide window.

print("Message Box in Console")
messagebox.showinfo("Notification", "Hello World!") #msgbox

App.mainloop() #required.

在上面的示例中,我认为#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"相同。那是数组中的10个元素。

我的问题是:为什么此示例中的“数组长度”与“字符串长度”不同? 11的长度来自何处?导致这种情况的'c', 'h', 'o', 'p', ' ', 's', 'u', 'e', 'y', '\0'类型有什么特别之处吗?

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:3)

正确的答案如下

#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

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

函数wcslenwchar_t符号进行计数,直到遇到终止的零为止。运算符sizeof返回数组dinner占用的字节数(包括终止零)。

实际上,字符串长度为9,即从字符串长度中排除终止零。数组的结尾处有零,其中有wchar_t类型的10个符号。

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