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 = newint[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);
}
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 = newint[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;
}
}
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.