I've written a pretty basic code that takes a static array and does a specific thing to the array based on the users input. For each input, the numbers in the static array gets placed into a dynamic array, preforms the task on the dynamic array, outputs it to an output file, and deletes the dynamic array. My problem is the dynamic array doesn't seem to delete correctly because when I run more than one task, it seems to recognize the array from the previous task instead of going back to the original static array.
case 1:
{
ifstream infile("input.txt");
infile>>number;
while(!infile.eof()){
++n; //used to count the size of the array
infile>>number>>a2[k]; //puts the numbers from input file into the static array
}
i=0; //bring back the menu
break;
}
case 2:
{
long* a=newlong[MAXSIZE]; //declare dynamic array a
for(k=0;k<n;++k)a[k]=a2[k]; //set array a = to a2
// perform a task on array a
ofstream outfile("output1.txt.");
for(j=0;j<n;++j){
outfile<<a[j]<<" ";} //place array a in output file
delete []a; //delete array a
a=NULL; //set it to NULL
i=0; //bring back menu
break;
}
case 3:
{
long* a=newlong[MAXSIZE]; //declare dynamic array a
for(k=0;k<n;++k)a[k]=a2[k]; //set array a = to a2
// perform a different task on array a
ofstream outfile("output2.txt.");
for(j=0;j<n;++j){
outfile<<a[j]<<" ";} //place array a in output file
delete []a; //delete array a
a=NULL; //set it to NULL
i=0; //bring back menu
}
}
The delete [] operator simply releases the previously allocated memory and hands it back to the operating system for potential reuse. It doesn't alter the contents of the block of memory (at least not for simple types such as an array of long).
It's entirely possible that a later use of new might receive the same address that was previously used. However the contents of that block of memory at this stage should be regarded as garbage.
By the way, to read integers from a file into an array, you could do this:
1 2 3 4
ifstream infile("input.txt");
n = 0;
while (infile >> a2[n])
n++;