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.
#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
#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 = newint[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 = newint[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.
int *tmp = newint[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'
}