Reputation: 30123
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.
Upvotes: 1
Views: 3168
Reputation: 32494
In the C family of languages the memory spaces which represent strings ( char arrays
) are terminated by the null character \0
Thus 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 \0
tacked onto their end by the system automatically and therefore need additional space.
Upvotes: 6
Reputation: 16305
Because string constants must store a NUL at the end of string, 2 chars of storage is not enough, hence the overflow. You need to store '1', '2', and NUL which is 3 chars.
Upvotes: 2
Reputation: 32639
That's because literal strings in C and C++ have an implied '\0' appended to them. It's called a zero-terminated string, it helps when trying to keep track of the length of the string, instead of storing it explicitly somewhere in memory.
Upvotes: 3
Reputation: 3049
The char array has a null terminating character "\0" at the end of every string. You always need to reserve an additional space in your array for this character.
Upvotes: 3