Function for dynamic array

Hello, my program is currently error free but I must have made a mistake with the pointers or something as it 's crashing when compiling. The program is supposed to have a function that takes two parameters, a reference to a pointer that is a dynamically allocated array of doubles. The function should replace the array with one that is twice as large. It also needs to prevent memory leaks.

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
 #include <iostream>

using std::cout;
using std::endl;

void growArray(double*& newArray, int size)
{
	 int newSize = size;
	 double* array = new double[size];

	double* array2 = new double[size];

	for (int i = 0; i < size; i++)
	{
		array2[i] = array[i];
		delete[] array;
		size = size * 2;
		array = new double[size];
		for (int i = 0; i < size - 1; i++)
		{
			array[i] = array2[i];
			delete[] array2;

		}
	}
} 



int main()
{
	double* myArray = new double[3];
	for (int i = 0; i<3; i++)
		myArray[i] = (i + 1) * 2;

	growArray(myArray, 3);

	for (int i = 0; i<6; i++)
		cout << myArray[i] << endl;

	delete[] myArray;

	return 0;
}


Thanks for the help!
Your logic is far to complicated. Also using meaningful names makes it easier.
Try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void growArray(double*& oldArray, int size)
{
  int newSize = size * 2; // calc new size

  double* newArray = new double[newSize]; // create new array

  // copy old array to new array
  for (int i = 0; i < size; i++)
  {
    newArray[i] = oldArray[i];
  }  
  // fill the remaining spots 
  for (int i = size; i < newSize; i++)
  {
    newArray[i] = (i + 1) * 2;
  }

  delete [] oldArray; // get rid of the old one

  oldArray = newArray; 
} 

OUTPUT

2
4
6
8
10
12
Press any key to continue . . .
Topic archived. No new replies allowed.