开发者

why is this syntax exclusively used to initialize string literals and can't be used for an array of characters? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Du开发者_C百科plicate:

initializing char arrays in a way similar to initializing string literals

below is a sample of initializing a string literal in which a terminating null character is added at the end of string, necessarily:

char reshte[]="sample string";

I wonder why can't we initialize an array of characters without terminating null character, in that way and we have to use the following syntax instead, that is exhausting in case there is a large number of characters:

char reshte[]={'s','a','m','p','l','e',' ','s','t','r','i','n','g'};


That is because in C characters inside "" are considered a string and a string is terminated by zero.

char reshte[]={ '1', '2', '3', '4' };

is also efficient and does what you expect.


I don't understand why you need the string without the terminating character so badly. Storage/performance wise, it doesn't make it an issue. You can just work knowing there's a null character at the end you don't need for your application, if you want to use that instantiation.

Or you could maybe do something like:

char reshte[]="sample strin";
reshte[strlen(reshte)]='g';


I wonder why can't we initialize an array of characters without terminating null character

Which language are we talking about? If you manually supply the length, you can do it in C:

char reshte[13]="sample string";

This is an error in C++ though.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜