焦炭和char的区别[1] [英] Difference between char and char[1]
问题描述
在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];
};
执行同样的原因遵循无符号的字符?
Do the same reasons follow for unsigned char?
推荐答案
的主要区别就是你用来访问一个字符的语法。
The main difference is just the syntax you use to access your one char.
通过访问我的意思是,法案后,它在语言使用不同的运营商,当适用于大部分或所有这一切都做不同的事情有比字符
字符
阵列。这使得它听起来好像 X
和是
几乎完全不同。如果事实上他们都包含一个字符,但字符已经重新在一个非常不同的方式psented $ P $。
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
但事实上,是
不分配不停止 SomeStruct
被分配:
b = a; // OK
这一切都是不分类型,字符
与否。一个类型的对象,并且该类型与尺寸1的阵列,是pretty大体相同中的什么在存储器术语
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.
顺便说一句,有在它使一个很大的区别,你用出来的字符
和字符的背景下[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
在栏的声明提供的数字
和巴兹
完全由C ++语言忽略。显然有人在某个时候认为,这将是程序员的文档的形式非常有用,这表明功能巴兹
期待它的指针参数指向的第一个元素阵列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.
在酒吧和巴兹, C
从来没有数组类型 - 它看起来像一个数组类型,但它不是,它只是用一个花哨的特殊情况下的语法同样的含义的char * 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.
这篇关于焦炭和char的区别[1]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!