Array output issue

Hi, I've designed a program that creates an array of a particular size specified by the user. This array is then passed to a function that copies the contents of the array and adds them to a larger array. What is weird and what I can't figure out is why when I make the array of size 2 I get some strange output. If I select an array of any other size, the new array contents (the larger array with the copied values from the original array) is made up of zeros. Can anyone explain why an array of size 2 yields the following output?

Output when 2 is entered for array size:
1
2
3
4
5
Enter the size of the array: 2
Initial Array Size: 2
Initial Array Contents: 22 25 
New Array Size: 4
New Array Contents: 22 25 16253272 0 


Other Output:
1
2
3
4
5
Enter the size of the array: 3
Initial Array Size: 3
Initial Array Contents: 58 99 42 
New Array Size: 6
New Array Contents: 58 99 42 0 0 0  


1
2
3
4
5
Enter the size of the array: 4
Initial Array Size: 4
Initial Array Contents: 37 16 30 29 
New Array Size: 8
New Array Contents: 37 16 30 29 0 0 0 0 


Program Code:
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
#include <iostream>
#include <algorithm>
#include <string>
#include <time.h>

using namespace std;

void doubleArray(int*, int);

int main() {

	int arrSize;

	cout << "Enter the size of the array: ";
	cin >> arrSize;

	int *initialArray = new int[arrSize];

	srand(static_cast<int>(time(NULL)));

	cout << "Initial Array Size: " << arrSize;
	cout << "\nInitial Array Contents: ";
	for (int j = 0; j < arrSize; j++) {

		int randNums = rand() % 100;
		initialArray[j] = randNums;

		cout << initialArray[j] << ' ';
	}

	doubleArray(initialArray, arrSize);

	return 0;
}

void doubleArray(int* arr, int size) {

	int doubleSize = size * 2;

	int* newArray = new int[doubleSize];

	for (int i = 0; i < size; i++) {

		newArray[i] = arr[i];
	}

	cout << "\nNew Array Size: " << doubleSize;
	cout << "\nNew Array Contents: ";
	for (int j = 0; j < doubleSize; j++) {

		cout << newArray[j] << ' ';
	}

	delete[] arr;
	arr = newArray;
}
Topic archived. No new replies allowed.