The assignment was to use a dynamic array to display the Fibonacci sequence backwards. Everything works except part of the assignment was to allocate and de-allocate elements. I tried to do this using the delete[] v; but it keeps triggering a break point and shows CrtIsValidHeapPointer error. I have no idea why its doing this and I'v tried playing around with my code to figure it out. I'm wondering if I allocated the elements wrong?
//Use a local array of size 20 to store the sequence of numbers and then print the sequence in reverse order (largest number first);
//display 6 numbers per line and use 5 positions for each number;
//Your program should make sure that length the series (i.e., the int being passed to the Fibonacci function) is >= 2 and <= 20;
//otherwise your program should display a message that length is out of bounds and terminate the execution.
//one extra point if your program correctly allocates and deallocates a dynamic array for length elements instead of using a fixed size
//array of size 20 to hold the numbers in the Fibonacci series.
#include <iostream>
#include <iomanip>
usingnamespace std;
void Fibonacci(int);
int main( )
{
cout << "how many numbers in the Fibonacci Series? ";
int n; // n numbers in the Fibonacci Series
cin >> n;
Fibonacci( n );
system("pause");
return 0;
}
// the rest of your program...
void Fibonacci(int n)
{
int *v = 0;
int p;
int l=0;
int first = 1;
int second = 1;
v = newint[n-3];
if(n>=2, n<=20)
{
v[0]=1;
v[1]=1;
for(int i=2; i<=n; i++)
{
p = v[i-2] + v[i-1];
v[i] = p;
}
cout << n << " numbers of the Fibonacci sequence in reverse order: " << endl;
while(n > 0, n--)
{
if(l < 6)
{
cout << v[n] << " ";
l++;
}
elseif(l > 6 && l < 12)
{
cout << v[n] << " ";
l++;
}
elseif(l > 12 && l < 18)
{
cout << v[n] << " ";
l++;
}
elseif(l > 18)
{
cout << v[n] << " ";
l++;
}
else
{
cout << endl << v[n] << " ";
l++;
}
}
}
else
{
cout << "Please enter a number 2 from 20";
exit(0);
}
cout << endl;
delete[] v;
}
Consider the loop at line 43. The last time through the loop, i==n so line 46 does v[n]=p. But at line 38 allocates space for only n-3 elements, making the largest valid index n-4.