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.

Recommended Answers

All 4 Replies

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
Aborted

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?

Thanks

Yes, thats the point of a debugger...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.