I'm not understanding why the string provided for initialization is too long?
Code:int main() { char array[1] = "A"; return 0; }
I'm not understanding why the string provided for initialization is too long?
Code:int main() { char array[1] = "A"; return 0; }
"Simplicity is the ultimate sophistication." - Leonardo da Vinci
C-string are terminated with a null character ('\0'). You don't have enough room in the array for the compiler to include this.
So when I have a string in quotes, there is an implied null byte at the end?
"Simplicity is the ultimate sophistication." - Leonardo da Vinci
Yes, at least for an initialization of a char array, since that is the definition of a C-string (char array terminated with a null character). However, I'm not a C++ person, so I'm not qualified to speak about C++ strings in general.
See for yourself:
Code:#include <iostream> int main() { char array[2] = "A"; if(array[1] == '\0') std::cout << "null char\n"; return 0; }
Last edited by Matticus; 05-09-2014 at 02:08 PM.
Well, there is a slight difference in that in C, the string literal would not be too long, but rather array would be initialised such that array[0] would have the value of 'A', since the null character implied in the string literal is only used for initialisation if there is sufficient space, unlike in C++.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
In other words, this is legal in C:
char array[1] = "A";
but not in C++.
But beware that if it was legal, you no longer have a C-style string, so attempts to use this as a string (using string functions such as strcpy, stcat, etc, or even initializing a std::string with it, e.g. std::string s(array)) will result in undefined behaviour.
There are ways around it, but the point is be careful. If at all possible, don't do it at all.