Array Length exceeded?

Hi all, I am new to C++ and I have a doubt.

1
2
3
    int scores[2];
    scores[5] = 23;
    cout << scores[5] << endl;


Shouldn't the above code be generating an error since I am exceeding the limit of Array i.e 2.
It Successfully shows the output "23".
I am using DevC++.
Waiting for your reply.................
Read more about pointers.

When you declare variable:
int scores[2];
scores keep an address of memory allocated to this variable, for example:
scores = 0x80000000
by writing scores[0], [1], [2], etc. to this address is added a step, which is size in byte of variable type. In this case it is int, which is 4 bytes.
1
2
3
4
scores[1] is 0x80000004
scores[2] is 0x80000008
..
scores[5] is 0x80000014


So by writing scores[5] = 23 you just set value to non or allocated memory.

It is programmer job to check array index when writing to it
Last edited on
Shouldn't the above code be generating an error since I am exceeding the limit of Array

It doesn't generate an error simply because the subscript is larger than the size of the array, as there is no code which performs that check - you have to write it yourself.

However, modifying memory which is not owned by the program will cause an error, but the nature of that error is unpredictable. It could corrupt some other data and hence cause some apparently unrelated code to misbehave.

Or the program may execute with no visible sign of error (though the code is still wrong) and may go undetected until you start to demonstrate the program to your boss, or to an important customer, when it will almost certainly crash in a spectacular fashion :)
Last edited on
closed account (NyhkoG1T)
I use VC++ 2010 Express and if I do something like that, it will throw up an error and end the program. Check your compiler options and see if you can increase the warning/error level. Also, if your using the beta 5 of dev C++, may I suggest switch down to an earlier, more stable version as that compiler hasn't been actively developed in years.

MS Visual C++ 2010 Express is a free version, and if you don't get a FREE key from Microsoft, it works for 30 days. A quick and easy registration will get you unlimited access. You can also download most of the other stuff that would come with a professional edition, for free, from the Microsoft site in individual packages to make one large complete package.

Don't forget SP1 : http://www.microsoft.com/en-us/download/details.aspx?id=8328

64-bit patch for SP1 (if needed) : http://www.microsoft.com/en-us/download/details.aspx?id=4422

Windows SDK:http://www.microsoft.com/en-us/download/details.aspx?id=8279
if you want the extra headers, compilers, code samples and help system.
Oh, I get it now.
Thank you all :)
Topic archived. No new replies allowed.