I have a pointer to an array of integers...

double* three = new double[10];
				for(int i = 0; i< 12;i++)
					three[i] = i+1;

I assign i+1 to each place in 'three'...when I debug the code, I cannot see the values inside 'three' like in C#..it just shows me the very first element in the array which is always 1!

Also why doesn't the above code throw an exception because surely when I am saying loop 12 times, I have only declared space for 10 ints?

Anyone shed a bit of light on this for me...if you can point me to some good literature about this sort of thing in C++ I would be most grateful, thanks.

6 Years
Discussion Span
Last Post by jbennet

C++ does not prevent you from accessing outside the bounds of an array. If you want exceptions on bounds checks look into standard containers that provide this type of thing. Here is an example using std::vector.at()

#include <vector>

int main () {
    std::vector< int > v(10);
    for (int i = 0; i < 12; ++i)
        v.at(i) = i + 1;
    return 0;

Running the above yields

terminate called after throwing an instance of 'std::out_of_range'
  what():  vector::_M_range_check

When you go outside the bounds of an array, you simply overwrite variables you shouldn't. You get an exception when you've overwritten enough to leave your dataspace and try to write outside of the program's assigned data space.

Expand your loop to 100 or more and you'll probably get your exception.


Thanks for this....my other question...is there a way to see the contents of the array using the visual studio debugger?


This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.