the following are my program
since it's not large, it might be alright to post the entire code?
anyway... it is the deallocate() causing the crash at the end of the program
for some reason, it did not panic in the grow() function
am I supposed to do something after the deallocate()?
// CS 540, HW #4, Joseph Chien
#include <iostream>
using namespace std;
struct GrowableArray
{ unsigned elements;
double *element;
};
void initialize(GrowableArray &a);
void grow(GrowableArray &a, unsigned newSize);
void deallocate(GrowableArray &a);
void show(const GrowableArray &a);
double get(const GrowableArray &a, unsigned index);
double set(GrowableArray &a, unsigned index, double value);
int main () {
GrowableArray g;
initialize(g);
grow(g,2);
set(g,1,1.1);
cout<<get(g,1)<<endl;
set(g,0,2*get(g,1));
grow(g,4);
show(g);
deallocate(g);
system("PAUSE");
return 0;
}
void initialize(GrowableArray &a)
{ unsigned zero=0;
a.elements=zero;
a.element=NULL;
}
void grow(GrowableArray &a, unsigned newSize)
{ if(newSize<a.elements)
{ cerr<<"Invalid input.\n";
exit(EXIT_FAILURE); }
double newE[newSize];
for(unsigned i=0; i<a.elements; i++)
newE[i]=a.element[i];
for(unsigned j=a.elements; j<newSize; j++)
newE[j]=0;
deallocate(a);
a.element= new double[newSize];
a.elements=newSize;
for(unsigned k=0; k<newSize; k++)
a.element[k]=newE[k];
}
void deallocate(GrowableArray &a)
{ for(int i=0; i<a.elements; i++)
delete[] &a.element[i];
}
void show(const GrowableArray &a)
{ cout<<"["<<a.elements<<"]: ";
for(int i=0; i<a.elements; i++)
cout<<a.element[i]<<", ";
cout<<endl;
}
double get(const GrowableArray &a, unsigned index)
{ if(index>a.elements)
{ cerr<<"Invalid input.\n";
exit(EXIT_FAILURE); }
return a.element[index];
}
double set(GrowableArray &a, unsigned index, double value)
{ if(index>a.elements)
{ cerr<<"Invalid input.\n";
exit(EXIT_FAILURE); }
a.element[index]=value;
}
// Output
/*
*/