views:

102

answers:

3

Possible Duplicate:
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'};
A: 

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.

FredOverflow
I'm talking about c++.
Pooria
+4  A: 

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.

stefaanv
+1 - for a concise response
ChrisBD
A: 

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';
Colin DeClue
@Colin DeClue: so you mean, not using that terminating null character is not a poor software design ?
Pooria
It's probably a terrible software design decision. But it can be made in specific scenarios. Something to consider: If there's someone who's going to maintain your code, they have to be able to follow it easily. "Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live."
Colin DeClue
@Colin DeClue: yeah you're right, I wouldn't want to argue with someone like that!!!
Pooria
@Colin DeClue: violent psychopath... excellent, I've got to remember that one. +1.
DevSolar