Im trying to Increase and Decrease the size of an array

Im trying to do my homeworks and its basically this. First I try to double the size of my array (from 5 to 10) then I try to decrease the size of it by Only one element.

This is what Ive done.
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
  int size = 5;
int theKingOfKeepingSizes = size;
string *arr = new string[size];

size = size + 5;

string *arr2 = new string[size];


for (int i = 0; i < theKingOfKeepingSizes; i++)
{
    arr2[i] = arr[i];
}

delete[] arr;

arr = arr2;

int newsize = size - 1;
string *arr3 = new string[newsize];

for (int i = 0; i < newsize; i++)
{
    arr3[i] = arr2[i];
}

delete[] arr2;

arr2 = arr3;


Before you tell me "vector" can be used, I know. Im just following instructions. Am I doing it right though? If Im not, what can I improve, and. If Im doing it right, how can I put it to test? with names maybe? Im unsure on how to do that.

Thank you!
you invalidated `arr' at line 27.
the client should only have to worry about calling your expand and shrink functions, and not having to follow all those temporaries.
Expanding on what ne555 said, it would be cleaner if your wrote a function to resize your array:
1
2
3
4
5
6
// Given an array arr with size elements, resize it
// to contain newSize elements. This creates a new array with newSize elements
// and copies the appropriate number of elements from arr to it. The original
// array is deleted and then arr and size are modified to contain the
// new values
string *resize(string * &arr, int &size, int newSize);

Once you have this, your code becomes
1
2
3
string *arr = new string[size];
resize(arr, size, 10);
resize(arr, size, size-1);
Topic archived. No new replies allowed.