开发者

Char array initialization dilemma

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 stan开发者_C百科dard.


This

char symbols[3] = "123";

is a valid statement.

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.

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

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

are identical to

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

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

The C99 specification draft can be found here.


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) 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜