Deallocating Pointers with Arrays

Apr 8, 2015 at 8:39pm
I need to deallocate arrayPtr in my addNumber function. I know I'm supposed to use delete to somehow deallocate it, but when I run my program it removes 10 from *arrayPtr or *p and does not show the number 55 in the last slot of the array. When I print out *p before I set *arrayPtr to equal *p it prints out all the numbers like this 0 10 20 30 40 55, but after I do that it prints them out as 0 0 20 30 40 0. I can't figure it out. If someone could point my in the right direction of how to deallocate *arrayPtr that would be great!

1
2
3
int check(int *arrayPtr, int number, int size);

void addNumber(int *& arrayPtr, int number, int &size);


1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include "varArray.h"

using std::cout; using std::cin; using std::endl;

int main(){

	int size = 5;
	int *a = new int[5];

	a[0] = 0; a[1] = 10; a[2] = 20; a[3] = 30; a[4] = 40;
	addNumber(a, 55, size);
	cout << "Array after adding a new number: "; output(a, size);
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int check(int *arrayPtr, int number, int size) {
	for (int i = 0; i < size; i++) {
		if (arrayPtr[i] == number) {
			return i;
		}
	}
	return -1;
}
#include "varArray.h"

void addNumber(int *& arrayPtr, int number, int &size) {
	int a = check(arrayPtr, number, size);
	if (a == -1) {
		int *p = new int[size + 1];
		for (int i = 0; i < size; ++i) {
			p[i] = arrayPtr[i];
		}
		delete [] arrayPtr; //This is the line that I think is the problem
		p[size] = number;
		size = size + 1;
		*arrayPtr = *p;
	}
}
Apr 8, 2015 at 8:43pm
Hi there! You don't want to delete arrayPtr, you want to delete p!
Apr 8, 2015 at 8:52pm
Hi there! You don't want to delete arrayPtr, you want to delete p!

No, I think he has it right. The problem is line 21 in addNumber. It should be:
arrayPtr = p;
instead of
*arrayPtr = *p;
Apr 8, 2015 at 8:53pm
Thank you for responding! I just tried doing that and it fixed the 10 that was disappearing, but the 55 is still not showing up.
Apr 8, 2015 at 9:12pm
Oh good call dhayden didn't realize they were replacing the old array with the new copy... I suppose I ought to read more carefully!

@misskmarie using *arrayPtr = *p; tries to copy the value of the thing p is pointing to into the thing arrayPtr is pointing to, without the * you change the thing arrayPtr points to toward what p points to. If you're using standard c++ and not c you may want to seriously consider using a vector instead of a plain array, it will make your life much easier.
Apr 8, 2015 at 9:12pm
dhayden thank you for our help! Your solution worked!
Apr 8, 2015 at 9:16pm
ultifinitus Thanks for the explanation. It makes a lot more sense now!
Topic archived. No new replies allowed.