为什么 char 不是单个字符? [英] Why is char not a single character?
问题描述
在 DEV_BROADCAST_DEVICEINTERFACE_A dbcc_name
的类型定义如下:
In Microsoft's documentation for DEV_BROADCAST_DEVICEINTERFACE_A the type of dbcc_name
is defined as follows:
char dbcc_name[1];
但如这个 StackOverflow 问题所示,结果是一个 string
带有 多个字符.
But as shown in this StackOverflow question it turns out to be a string
with multiple characters.
char
不是 16 位值 单个字符吗?这是如何工作的?
Isn't a char
a 16 bit value single character? How does this work?
(我原本以为 char
是 16 位.大概是因为这是它在 c# 中的大小.实际上可能是因为我在看 DEV_BROADCAST_DEVICEINTERFACE_W 其中确实是 2 个字节.)>
(I had originally thought that char
is 16 bits. Presumably because that's its size in c#. Actually it was probably because I was looking at DEV_BROADCAST_DEVICEINTERFACE_W where it is indeed 2 bytes.)
推荐答案
char
不是一个 16 位的值吗?
Isn't a
char
a 16 bit value?
在什么平台上?在大多数平台上(包括所有运行 Windows 的平台,AFAIK),char
是 8 位.
On what platform? On most platforms (including all that run Windows, AFAIK), char
is 8 bits.
这是如何工作的?
类型文档解释了这一点:
The type documentation explains this:
这个结构的大小,以字节为单位.这是成员的大小加上 dbcc_name 字符串的实际长度(空字符是通过将 dbcc_name 声明为单字符数组来考虑的.)
dbcc_size
The size of this structure, in bytes. This is the size of the members plus the actual length of the dbcc_name string (the null character is accounted for by the declaration of dbcc_name as a one-character array.)
换句话说,_DEV_BROADCAST_DEVICEINTERFACE_A
的定义利用了C++中数组衰减为指针的事实,因此具有数组类型的dbcc_name
可以用作大多数情况下以零结尾的字符串.实际字符串与 _DEV_BROADCAST_DEVICEINTERFACE_A
对象连续存储在从 dbcc_name
偏移量开始的地址处.
In other words, the definition of _DEV_BROADCAST_DEVICEINTERFACE_A
exploits the fact that arrays decay to pointers in C++, and thus dbcc_name
, which has array type, can be used as a zero-terminated string in most contexts. The actual string is stored contiguously with the _DEV_BROADCAST_DEVICEINTERFACE_A
object, at the address starting at the offset of dbcc_name
.
值得注意的是,数组(1)的大小与其内容的长度无关;它只是 C++ 中最小的合法静态数组大小(遗留代码偶尔会使用 char[0]
类型的结构成员.但是,这是编译器扩展而不是合法的 C++).
It’s worth noting that the size of the array (1) is unrelated to the length of its contents; it is simply the smallest legal static array size in C++ (legacy code occasionally uses struct members of type char[0]
. However, this is a compiler extension and not legal C++).
这篇关于为什么 char 不是单个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!