Expanding an array

My problem is to take an array, expand it to double the size using a function, use that same function to return a pointer.

Here is the code I have so far

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
  //
//  main.cpp
//  Week 2 Assignment 2
//
//  Created by Adam Windsor on 8/29/14.
//  Copyright (c) 2014 Adam Windsor. All rights reserved.
//

#include <iostream>
#include <iomanip>
using namespace std;

//Prototypes

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

int main()
{
    const int SIZE = 5;
    int array1[SIZE] = {1,2,3,4,5};
    expandArray(array1, SIZE);
    
    return 0;
}

int* expandArray(int array1[], int size)
{
   
    int* array2;
    int expanded; // to double the array
    
    expanded = size *2;
    array2 = new int[expanded];
    
    for (int count = 0; count < expanded; count++) {
        array2[count] = array1[count];
        cout << array2[count] << " ";
    }
    
    
    return array2;
}



When I run the program, the output is 1,2,3,4,5,0,0,0,5,0. So I'm doing something right because the array is doubling in size! My first question is where is the 5 in the 9th spot coming from and how do I fix it to get it to display a 0?

Thanks

Adam
line 37 - the values of count (0 through 9) will be valid for array2 but not the original array1 which only has 5 elements. Going out of bounds on an array may have undefined results.

Only half the new array needs to be copied from the old one. Maybe you want to initialize the other half with 0?
Thank you for the reply.

Yes I was trying to get them all 0's. Your explanation cleared it up for me as to why that 5 was there.

Last edited on
Topic archived. No new replies allowed.