Dynamic Array Help

Hey.
I was just wondering whether the code shown below is the most effective way of increasing the size of an array, or whether it would even work at all.

Thanks.

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
 int* growArray(int* values, int* size);


int main()
{
	int nextElement = 0;
	int size = 5;

	int* p_values = new int[size];
	int val;
	cin >> val;

	while (val > 0)
	{
		if (size == nextElement + 1)
		{
			growArray(p_values, & size);
		}
		p_values[nextElement] = val;
		nextElement++;
		cin >> val;
	}

	for (int i = 0; i < size; i++)
	{
		cout << "Element " << i << " :" << p_values[i] << endl;
	}

	cin.get;
        Delete[] p_values;

	return 0;
}

int* growArray(int* values, int* size)
{
	*size *= 2;
	int* p_newValues = new int[*size];
	for (int i = 0; i < *size; i++)
	{
		p_newValues[i] = values[i];
	}
	return p_newValues;
}
Last edited on
The first thing that worries me is that the return value from growArray is ignored on line 17. The next thing that I noticed is a memory leak because the return value is ignored. The newly allocated memory is still allocated with no reference to it. Meaning it is not erased. I am going to pull up an old piece of code that has an example of this type of array. In the meantime, I must ask why do you not just use vectors?
http://www.cplusplus.com/reference/vector/vector/

ListArray.h:
http://pastebin.com/ByK2AHW5

ListArrayIterator.h:
http://pastebin.com/gBnzTfq4

Example usage:
1
2
3
4
5
6
7
8
9
10
11
12
13
ListArray<int>* list = new ListArray<int>();
int x = 0;
list->add(&x);

ListArrayIterator<int>* it = list->iterator();
while(it->hasNext())
{
    int* num = it->next();
    std::cout << *num << std::endl;
}
delete it;

delete list;


Honestly, I love vectors compared to dealing with that. That old code is something from a professor I found on the internet.
Last edited on
Hi, thanks for your response. I see what you mean about the return value from growArray, I should really have picked up on that. Anyway, on a separate issue, I was wondering why you would ever need to return a pointer as I understand that one of their key benefits is being able to reference the original variable rather than copying it.

After briefly reading into Vectors they look like a nice alternative, I'll have to give them a try!

Again, thanks for your help.
You can also return variables by reference using the ampersand (&) character.
http://www.cprogramming.com/tutorial/references.html
Topic archived. No new replies allowed.