开发者

Visual C++ 6.0 - Why array bounds overflow?

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'};
开发者_JAVA百科

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 \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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜