Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Suppose I've following initialization of a char array:

char charArray[]={'h','e','l','l','o',' ','w','o','r','l','d'};

and I also have following initialization of a string literal:

char stringLiteral[]="hello world";

The only difference between contents of first array and second string is that second string's got a null character at its end.

When it's the matter of initializing a char array, is there a macro or something that allows us to put our initializing text between two double quotation marks but where the array doesn't get an extra null terminating character?

It just doesn't make sense to me that when a terminating null character is not needed, we should use syntax of first mentioned initialization and write two single quotation marks for each character in the initializer text, as well as virgule marks to separate characters.

I should add that when I want to have a char array, it should also be obvious that I don't want to use it with functions that rely on string literals along with the fact that none of features in which using string literals results, is into my consideration.

I'm thankful for your answers.

See Question&Answers more detail:os

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

1 Answer

It's allowed in C to declare the array as follows, which will initialize it without copying the terminating ''

char c[3] = "foo";

But it's illegal in C++. I'm not aware of a trick that would allow it for C++. The C++ Standard further says

Rationale: When these non-terminated arrays are manipulated by standard string routines, there is potential for major catastrophe.
Effect on original feature: Deletion of semantically well-defined feature.
Difficulty of converting: Semantic transformation. The arrays must be declared one element bigger to contain the string terminating ’’.
How widely used: Seldom. This style of array initialization is seen as poor coding style.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...