Initialize unused elements with 0

Hello,

I have written a program that should create two arrays, one double the size, and initialize all unused elements in the new array with 0. That is the part I am having difficulty with. When it compiles, both arrays display the same contents. Any ideas on how to get the ten 0's I am looking for in the new array? Thank you.

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

using namespace std;

int *expandArray(int[], int);
void showArray(int[], int);

int main()
{
	const int size = 10;
	int array[size] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
	int *expand;

	expand = expandArray(array, size);

	cout << "Below is the original array " << endl;
	showArray(array, size);
	cout << "Below is the expanded array " << endl;
	showArray(expand, size);

	system("pause");
	return 0;
}

int *expandArray(int arr[], int size)
{
	int *expand;

	expand = new int[size * 2];
	memcpy(expand, arr, size * sizeof(int));
	for (int i = size; i < size * 2; i++)
		expand[i];

	return expand;
}

void showArray(int arr[], int size)
{
	for (int i = 0; i < size; i++)
		cout << arr[i] << " " << endl;
}
Last edited on
You always forgot to delete the dynamic array when your program needs it.

Edit :
1.
for (int i = size; i < size * 2; i++) expand[i];

Should be :
for (int i = size; i < size * 2; i++) expand[i] = 0;

2.
1
2
cout << "Below is the expanded array " << endl;
showArray(expand, size);


Should be :
1
2
cout << "Below is the expanded array " << endl;
showArray(expand, size * 2);
Last edited on
It displayed ten more elements, but they aren't 0. I get 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -842150541(x10)
Did you use this line?
for (int i = size; i < size * 2; i++) expand[i] = 0;

1
2
3
4
5
6
7
8
9
10
int *expandArray(int arr[], int size)
{
	int *expand;

	expand = new int[size * 2];
	memcpy(expand, arr, size * sizeof(int));
	for (int i = size; i < size * 2; i++) expand[i] = 0;

	return expand;
}
Nailed it, thank you!!
Topic archived. No new replies allowed.