I tried to compile it in VC++ 6.0, there is a compiler error. But a string could be terminated without '\0', couldn't it? Thanks.
Printable View
I tried to compile it in VC++ 6.0, there is a compiler error. But a string could be terminated without '\0', couldn't it? Thanks.
"abc" is 4 characters. 'a', 'b', 'c', '\0'.
Is one way of accomplishing that.Code:char s[3] = { 'a','b','c' };
This is asking for trouble unless you know what you are doing...Code:char s[3];
memcpy(s, "ABC", 3);
No char s[3] = "abc" is not legal since "abc" is a const char* (or at least considered as const).
the problem is not the fact that "abc" is a const literal; you can initialize fixed size char arrays with a const literal; the problem is that the to be initialized array must have sufficient characters to store the literal, including the null terminator;
for example, "char s[3] = "abc";" does not compile, but "char s[4] = "abc";", "char s[5] = "abc";", ... does compile and it's legal.
Eh, totally messed this up in my head... :o
Have lately changed a lot of legacy code due to deprecated warnings about char* being assigned with string literals. Seems like that has gotten to me worse than I thought... :sick:
why aren't you just writing:
?Code:char s[] = "abc";
but if you really don't want to waste that one byte (which is the '\0' character) you can also write like this:
it's pretty the same way as what Russco said ( char s[3] = { 'a','b','c' }; ) only that by the method I've shown you write a bit more.Code:char s[3];
s[0] = 'a';
s[1] = 'b';
s[2] = 'c';
Sure it's possible. But why would you want to? The concept of c-style strings revolves around them being null-terminated. The only time I can think of when you might even think about doing it is in the internals of a string class. In pretty much any other circumstance, you're just making more work for yourself.
Well, in C, this is valid:
being equivalent to:Code:char s[3] = "abc";
But I don't consider it advisable since readers may ask if it is valid.Code:char s[3] = {'a', 'b', 'c'};