char 和 char[1] 的区别

2022-01-12 00:00:00 arrays char c++ static-array

在 C++ 中,使用 char 和 char[1] 有什么区别(如果有的话).

In C++ what is the difference (if any) between using char and char[1].

例子:

struct SomeStruct
{
   char x;
   char y[1];
};

对于 unsigned char 是否有同样的原因?

Do the same reasons follow for unsigned char?

推荐答案

主要区别只是用于访问单个字符的语法.

The main difference is just the syntax you use to access your one char.

我所说的访问"是指使用语言中的各种运算符对其进行操作,与 char数组.这听起来好像 xy 几乎完全不同.如果事实上它们都由"一个字符组成,但该字符以非常不同的方式表示.

By "access" I mean, act upon it using the various operators in the language, most or all of which do different things when applied to a char compared with a char array. This makes it sound as if x and y are almost entirely different. If fact they both "consist of" one char, but that char has been represented in a very different way.

实现可能会导致其他差异,例如它可能会根据您使用的结构以不同的方式对齐和填充结构.但我怀疑它会.

The implementation could cause there to be other differences, for example it could align and pad the structure differently according to which one you use. But I doubt it will.

运算符差异的一个例子是 char 是可赋值的,而数组不是:

An example of the operator differences is that a char is assignable, and an array isn't:

SomeStruct a;
a.x = 'a';
a.y[0] = 'a';
SomeStruct b;
b.x = a.x; // OK
b.y = a.y; // not OK
b.y[0] = a.y[0]; // OK

y 不可赋值这一事实并不能阻止 SomeStruct 可赋值:

But the fact that y isn't assignable doesn't stop SomeStruct being assignable:

b = a; // OK

所有这些都与类型无关,char 与否.一个类型的对象和一个大小为 1 的类型的数组,就内存中的内容而言几乎相同.

All this is regardless of the type, char or not. An object of a type, and an array of that type with size 1, are pretty much the same in terms of what's in memory.

顺便说一句,您在 charchar[1] 中使用"它会产生很大的不同,有时会有所帮助使人们误以为数组实际上是指针.不是您的示例,而是作为函数参数:

As an aside, there is a context in which it makes a big difference which you "use" out of char and char[1], and which sometimes helps confuse people into thinking that arrays are really pointers. Not your example, but as a function parameter:

void foo(char c);     // a function which takes a char as a parameter
void bar(char c[1]);  // a function which takes a char* as a parameter
void baz(char c[12]); // also a function which takes a char* as a parameter

barbaz 的声明中提供的数字被 C++ 语言完全忽略.显然有人在某些时候觉得它作为一种文档形式对程序员很有用,表明函数 baz 期望它的指针参数指向 12 字符数组的第一个元素.

The numbers provided in the declarations of bar and baz are completely ignored by the C++ language. Apparently someone at some point felt that it would be useful to programmers as a form of documentation, indicating that the function baz is expecting its pointer argument to point to the first element of an array of 12 char.

在 bar 和 baz 中,c 从来没有数组类型――它看起来像一个数组类型,但实际上不是,它只是一种花哨的特殊情况语法,与 含义相同字符 *c.这就是为什么我将引号放在使用"上 - 你根本没有真正使用 char[1],它只是看起来像它.

In bar and baz, c never has array type - it looks like an array type, but it isn't, it's just a fancy special-case syntax with the same meaning as char *c. Which is why I put the quotation marks on "use" - you aren't really using char[1] at all, it just looks like it.

相关文章