I’m new to C++ and I have to use array. The problem is I get error “array bounds overflow” in this line:
char arr[2] = "12";
But when I changed it to:
char arr[3] = "12";
it works fine but why?
Update:
And this works 🙁
char arr[2] = {'1','2'};
I’m really confused about the difference between declarations, how they are stored in the memory.
In the C family of languages the memory spaces which represent strings (
char arrays) are terminated by the null character\0Thus the memory to store the string must be at least one character larger than the expected size when you write it out with
" "Your new example, isn’t creating a string, but rather an array of characters. Because you have switched notations form
" "to{ }the system is no longer creating a null terminated string but is rather creating an array as that is what you have asked for.The crux of it is that Strings are special and have
\0tacked onto their end by the system automatically and therefore need additional space.