Reputation: 231
Got a bit of code here thats giving me a runtime error that I cant seem to fix. The function Length() calculates the cumulative distance between all the points in an array of points. It uses a previously defined function Distance() that I know works perfectly. Any pointers?
Here is my source code for the function:
template<typename Point> //Length function
double PointArray<Point>::Length() const
{
double total_length = 0;
for (int i=0; i<Size(); i++)
{
total_length += (GetElement(i)).Distance(GetElement(i+1));
}
return total_length;
}
And here is my implementation:
cout<<"The Length of the Point Array is: "<<(*ptArray1).Length()<<endl;
Many thanks!
Upvotes: 0
Views: 64
Reputation: 20063
You are reading elements that are beyond the end of the array.
for (int i=0; i<Size(); i++)
{
total_length += (GetElement(i)).Distance(GetElement(i+1));
//^^^
}
One you reach the end of the for
loop you read the last element and then calculate the distance from the next element - which is outside the bounds of the array . Your for
loop should look something like this:
for (int i=0; i<Size() - 1; i++)
{
total_length += (GetElement(i)).Distance(GetElement(i+1));
}
Upvotes: 3
Reputation: 23634
Try this:
template<typename Point> //Length function
double PointArray<Point>::Length() const
{
double total_length = 0;
for (int i=0; i<Size()-1; i++)
{ //^^^ otherwise, i+1 will be out of range
total_length += (GetElement(i)).Distance(GetElement(i+1));
}
return total_length;
}
Upvotes: 2