Please help (Pointers, Arrays, Dynamic Memory Allocation)

I'm finishing this program that adds to and removes from and array using pointers but and I have figured how to code all of the required functions except the function for removing the element of the array.

This is the header file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  #ifndef VARARRAY_H
#define VARARRAY_H

// prints the values in "arrayPtr" of "size" 
void output(int *arrayPtr, int size);

// returns the index of the element in "arrayPtr" of "size"
// that corresponds to the element holding "number"
// if number is not in the array, returns -1
int check(int *arrayPtr, int number, int size);

// adds "number" to the array pointed to by "arrayPtr" of "size". 
// if the number is not already there, if "number" is there - no action
// Note, the size of the array is thus increased. 
void addNumber(int *& arrayPtr, int number, int &size);

// removes a "number" from the "arrayPtr" of "size".
// if "number" is not there -- no action
// note, "size" changes
void removeNumber(int *& arrayPtr, int number, int &size);

#endif // VARARRAY_H 


and these are my functions:
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
#include "varArray.h"
#include <iostream>

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

void output(int *arrayPtr, int size) {
	for (int i = 0; i < size; ++i) {
		cout << arrayPtr[i] << ' ';
	}
	cout << endl;
}

int check(int *arrayPtr, int number, int size) {
	for (int i = 0; i < size; ++i) {
		if (arrayPtr[i] == number)
			return i;
	}
	return -1;
}

void addNumber(int *& arrayPtr, int number, int &size) {
	if (check(arrayPtr, number, size) == -1) {
		int *tmp = new int[size + 1];
		for (int i = 0; i < size; ++i)
			tmp[i] = arrayPtr[i];
		tmp[size] = number;
		size++;
		delete[] arrayPtr;
		arrayPtr = tmp;
	}
}

void removeNumber(int *& arrayPtr, int number, int &size) {
	if (check(arrayPtr, number, size) != -1) {
		int tmpV = check(arrayPtr, number, size);
		int *tmp = new int[size - 1];
		for (int i = 0; i < size; ++i) {
			if (arrayPtr[i] != tmpV)
				tmp[i] = arrayPtr[i];
		}
		delete[] arrayPtr;
		arrayPtr = tmp;
	}
}


I know that what I have for my removeNumber function is wrong but I can't figure out how to fix it, any help you could provide would be much appreciated.
> I know that what I have for my removeNumber function is wrong
¿why do you say that? ¿what's wrong with the function?
Whenever I run the program a pop-up message appears and says that there was a debug error
1
2
3
4
5
		int *tmp = new int[size - 1];
		for (int i = 0; i < size; ++i) {
			if (arrayPtr[i] != tmpV) //tmpV is an index, not an element
				tmp[i] = arrayPtr[i]; //out of bounds, `i' may be `size-1'
		}
http://www.cplusplus.com/forum/general/112111/#msg612043
Last edited on
Topic archived. No new replies allowed.