Dynamic array won't delete

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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=new long[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=new long[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
}
}
Last edited on
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++;
Last edited on
Offtopic... but OP... you really shouldn't be so afraid of whitespace.

Formatting that code would make it a million times easier to read.
... I had some time to spare, I copied the code into an editor and re-formatted it before attempting to read it. :)
It was from copying and pasting from my editor, my bad I'll clear it up here.
Topic archived. No new replies allowed.