I need help with a function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void removeNumber(int *& arrayPtr, int number, int &size) {
	if (check(arrayPtr, number, size) != -1) {
		int tmpV = check(arrayPtr, number, size);
		int *tmp = new int[0];
		for (int i = 0; i < size; ++i) {
			if (arrayPtr[i] != arrayPtr[tmpV])
				tmp[i] = arrayPtr[i];
			else if (arrayPtr[i] == arrayPtr[tmpV])
				tmp[i] = arrayPtr[i + 1];
		}
		size--;
		delete[] arrayPtr;
		arrayPtr = tmp;
	}
}


The function is supposed to take an already existing array and remove one of the elements (chosen by the user) of that array as it copies it to a new, smaller, array and ultimately gets copied back onto the existing array. I've built it so it isn't a build time error but when I'm running the program a message pops up and informs me that there is a debugging error.
The function logic is ok, but the problem is in line 4
int *tmp = new int[0];
you allocate not enougn space here, and write outbound your memory.
I changed 0 to 10, and found no debugging error here.

using new here is not a good thing.
Here is a standard way of removing number:
1
2
3
    std::vector<int> v = { 1, 2, 3 };
    v.erase(std::remove(v.begin(), v.end(), 1), v.end());
    std::for_each(v.begin(), v.end(), [](int i) {std::cout << i; });


hoping this will help:)
Last edited on
Topic archived. No new replies allowed.