Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

c - 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 standard.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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', '' },
t[] = { 'a', 'b', 'c' };

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

The C99 specification draft can be found here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...