"resizable" array

I'm trying read an array of a size unbeknownst to me.To start reading in the values of the array, I start out with a size of 10, and when I reach capacity I call a function to resize the array. Here's where I'm having trouble when I call the function, it resizes the array once and stops reading in the rest of the values. On top of that, when I try to add the values the program did managed to read in, I get a negative number. If anyone could point me in the right direction, I would be very thankful.
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
#include <iostream>
#include <fstream>
using namespace std;

void resize(int*,int&);

int main()
{
    ifstream in("numbers.input");

    int counter=0;
    int size = 10;
    int *arr = new int [size];
    double avg;
    int total = 0;

    for(int i =0; i < size; i++){
        in>>arr[i];
        total+=arr[i];
        counter++;
        if(counter == size){
            counter = 0;
            resize(arr,size);
        }
    }
    avg =(double) total/size;
    cout<<counter<<endl;
    cout<<size<<endl;
    cout<<total<<endl;
    cout<<avg;
    return 0;
}
void resize(int *arr,int &size) {
    size*=2;
    int* newArr = new int[size];
    for(int i = 0; i < size; i++){
        newArr[i] = arr[i];
    }
    delete [] arr;
    arr = newArr;
    delete [] newArr;
}
Why are you deleting your new array right after you populate it?

Move line 41 to between lines 30 and 31.

Hope this helps.
In resize you pass a pointer by value. You then change the value of that pointer. But, since the pointer was passed by value nothing outside of the function is affected. In main you still have a pointer to the memory that was deallocated in the function. Of course, if that wasn't the case you would still have an in valid pointer in main since you delete your newly allocated array before you leave resize.
Line 40: arr is a pointer that is passed by value. Setting it to newArr serves no purpose. Both arr and newArr go out of scope when resize() exits.

Line 41: Why are you deleting newArr after you just got through building it?

Line 42: You need some way of returning newArr back to main. The usual way to do this is to make resize return an int pointer (to newArr). Line 23 of course has to be changed to set arr to the return value from resize.

Yeah, what these guys say.

To fix the argument problem, use a reference:

void resize( int *& arr, int & size )
Topic archived. No new replies allowed.