Dynamic Arrays

Hello,

I'm working on a program to practice dynamic arrays. What I'm trying to do is have the user input numbers to fill an array that will double in size when it gets full. When the current array is full, the filled array should be copied to a temporary array, then deleted. A new array with double the size of the previous is then created, and then the values of the temporary array should be copied to the newly created array. The temporary array is then deleted, and the process should be repeated until the user inputs 0. When the user inputs 0, the program should display all the the numbers recorded in the array.

I'm doing something wrong, but I'm not sure where it is or how to fix it. I can only input 2 values before I get an error message saying "Debug Assertion Failed!". Even if I only input one number, when I input 0 to display the array I get long numbers that mean the elements don't exist.
Could anyone point me in the right direction as to what I need to do and/or what I'm doing wrong?

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include<iostream>
#include<iomanip>
#include<cstdlib>
using namespace std;

void main()
{
	int input;
	int size=2;
	int c=0;

	int *Dynarray;
	Dynarray=new int[size];

	cout<<"Enter values to fill an array. Enter 0 to end it."<<endl;
	
	do
	{
		cin>>input;

		if(input!=0)
		{
			
			if(c<size)
			{
			Dynarray[c]=input;
			c++;
			}

			if(c=size)
			{
				int* TempDynarray=new int[size];

				for(int i=0;i<size;i++)
				{
					TempDynarray[i]=Dynarray[i];
				}

				delete[] Dynarray;

				int* Dynarray=new int[size*2];

				for(int j=0;j<size;j++)
				{
					Dynarray[j]=TempDynarray[j];
				}

				delete[] TempDynarray;

				Dynarray[c]=input;

				c++;
			}
		}
	}
	while(input!=0);

	if(input==0)
	{
		for(int i=0;i<c;i++)
		{
			cout<<Dynarray[i]<<endl;
		}
	}

}


Thanks in advance!
Last edited on
I see problems with lines 30 and 41. There might be more, I am still a beginner as well.

line 30:
else

line 31:
Dynarray=new int[size *2];

You also forgot to change the value of size after creating a new array.
Last edited on
You also don't delete[] Dynarray after you output it at 60-63. Also, the if statement on 58 is completely pointless; the code could not have exited the while loop if input was not 0, so that if is unconditionally going to be entered as things are.

This is more of an efficiency point, but you could simply allocate TempDynarray is being the original array with *2 the size, copy Dynarray over, delete[] Dynarray, then simply set DynArray to point to the same array as TempDynarray. This saves you from having to copy all the elements back again.
Topic archived. No new replies allowed.