C++ newb here. I’m trying to write my own implementation of an array using only pointers, and I’ve hit a wall I don’t know how to get over.
My constructor throws this error
array.cpp:40:35: error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive]
When my array initializes I want it to free up all the spaces in the array for ints.
Array::Array(int theSize){
size = theSize;
int *arrayPointer = new int;
int index = 0;
while(theSize > index){
*(arrayPointer + index) = new int; //This is the trouble line.
++index;
}
}
What am I doing wrong stackoverflow?
arrayPointerpoints to a singleint, it does not point to an array ofint*, which this line would require:but the type of
*(arrayPointer + index)is anint, hence the compiler error.To allocate an array of
int:If this is intended to initialise a member variable then:
otherwise
arrayPointerwould be local to the constructor. As the class now has a dynamically allocated member you need to either implement both copy constructor and assignment operator or prevent copying (see What is The Rule of Three?). Remember todelete[] arrayPointerin the destructor.Just mentioning
std::vector<int>, even though this is a learning exercise.