Char 数组初始化困境
考虑下面的代码:
// hacky, since "123" is 4 chars long (including terminating 0)
char symbols[3] = "123";
// clean, but lot of typing
char symbols[3] = {'1', '2', '3'};
所以,扭曲实际上是在代码注释中描述的,有没有办法用字符串文字初始化char[]
而不以零结尾?
更新:看来 IntelliSense 确实是错误的,这种行为在 C 标准中明确定义。
Consider following code:
// hacky, since "123" is 4 chars long (including terminating 0)
char symbols[3] = "123";
// clean, but lot of typing
char symbols[3] = {'1', '2', '3'};
so, the twist is actually described in comment to the code, is there a way to initialize char[]
with string literal without terminating zero?
Update: seems like IntelliSense is wrong indeed, this behaviour is explicitly defined in C standard.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这
是一个有效的陈述。
根据 1988 年 ANSI C 规范:
因此,你所做的事情在技术上是没问题的。
请注意,字符数组是初始化器上规定的约束的一个例外:
然而,一段代码的技术正确性只是该代码“优点”的一小部分。
charsymbols[3] = "123";
行将立即让经验丰富的程序员感到怀疑,因为从表面上看,它似乎是一个有效的字符串初始化,并且以后可能会这样使用,导致意外错误和必死无疑。如果您想走这条路,您应该确定这是您真正想要的。节省额外的字节并不值得为您带来麻烦。 NULL 符号(如果有的话)允许您编写更好、更灵活的代码,因为它提供了一种明确的(在大多数情况下)终止数组的方式。
(规范草案可在此处获取。)
为了采纳 Rudy 在本页其他地方的评论,C99 规范草案§6.7.8(第 130 页)中的第 32 个示例指出,这些行
相同
与您可以从中推断出您正在寻找的答案
。 C99 规范草案可以在此处找到。
This
is a valid statement.
According to the ANSI C Specification of 1988:
Therefore, what you're doing is technically fine.
Note that character arrays are an exception to the stated constraints on initializers:
However, the technical correctness of a piece of code is only a small part of that code's "goodness". The line
char symbols[3] = "123";
will immediately strike the veteran programmer as suspect because it appears, at face value, to be a valid string initialization and later may be used as such, leading to unexpected errors and certain death.If you wish to go this route you should be sure it's what you really want. Saving that extra byte is not worth the trouble this could get you into. The NULL symbol, if anything, allows you to write better, more flexible code because it provides an unambiguous (in most instances) way of terminating the array.
(Draft specification available here.)
To co-opt Rudy's comment elsewhere on this page, the C99 Draft Specification's 32nd Example in §6.7.8 (p. 130) states that the lines
are identical to
From which you can deduce the answer you're looking for.
The C99 specification draft can be found here.
如果您的数组只有 3 个字符长,则第一行代码与第二行相同。字符串末尾的
'\0'
将不会被存储。 IOW,它没有什么“肮脏”或“错误”。If your array is only 3 chars long, the first line of code is identical to the second line. The
'\0'
at the end of the string will simply not be stored. IOW, there is nothing "dirty" or "wrong" with it.1)您提到的问题不是问题。
2) 问:有没有办法用字符串文字初始化 char[] 而不以零结尾? ——你已经在这么做了。
1) The problems you are mentioning are not problems.
2) Que: Is there a way to initialize char[] with string literal without terminating zero? -- you are already doing that.