字符数组初始化困境 [英] Char array initialization dilemma

查看:147
本文介绍了字符数组初始化困境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下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'};

所以,在扭曲的到code评论实际上是描述的,是有办法来初始化的char [] 用绳子文字不终止零?

so, the twist is actually described in comment to the code, is there a way to initialize char[] with string literal without terminating zero?

更新:好像智能感知是错误的确,这种行为在C标准明确定义

Update: seems like IntelliSense is wrong indeed, this behaviour is explicitly defined in C standard.

推荐答案

char symbols[3] = "123";

是一个有效的语句。

is a valid statement.

据1988年的ANSI C规格:

According to the ANSI C Specification of 1988:

字符类型的数组,可以用一个字符串被初始化
  文字,可选大括号括起来。的连续字符
  字符串文字(包括终止空字符,如果
  有空间,或如果阵列是未知大小的)初始化
  数组的成员。

An array of character type may be initialized by a character string literal, optionally enclosed in braces. Successive characters of the character string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the members of the array.

因此​​,你在做什么在技术上是很好。

Therefore, what you're doing is technically fine.

请注意该字符数组是一个例外规定的制约初始化:

Note that character arrays are an exception to the stated constraints on initializers:

有应比有一个初始化列表没有更多的初始化
  被对象被初始化

There shall be no more initializers in an initializer list than there are objects to be initialized.

然而,一件code的技术正确性仅仅是code的善的一小部分。行字符符号[3] =123; 将立即罢工的老程序员为可疑,因为它的出现,面值,是一个有效的字符串初始化和以后可能这样使用,从而导致意外错误和某些死亡

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.

如果你希望走这条路,你应该确保它是你真正想要的。节省额外的字节是不值得的麻烦,这可能让你进入。空符号,如果有的话,可以让你写出更好的,更灵活的code,因为它提供终止阵列的一个明确的(在大多数情况下)的方式。

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.

(规格可这里。)

要在其他地方增选鲁迪的评论页面上,C99的规范草案在§6.7.8(第130页)第32举例指出,行

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

char s[] = "abc", t[3] = "abc";

是相同的。

char s[] = { 'a', 'b', 'c', '\0' },
t[] = { 'a', 'b', 'c' };

从中可以推断出你正在​​寻找的答案。

From which you can deduce the answer you're looking for.

在C99规范草案可以在这里找到

The C99 specification draft can be found here.

这篇关于字符数组初始化困境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆