Reputation: 1
i have this problem, my program crashes after i started using this function. I don't know how to correctly return required type. Its a binary search in template. I tried changing it to T * search, cast array[middle]
to const and doing things like const T * out = &array[middle];
but whenever i add the &, it crashes. If i take it away and return only array[middle], it says:
cannot convert 'Fractions' to 'const Fractions*' in return
How should i return it correctly? i have array declared like this and this function is in the same class: It should work with any type, we were given class Fractions to test it, so its normal array of type Fractions, nothing fancy.
T * array;
and
const T *search(const T &inElement){
unsigned low = 0;
unsigned high = numberOfElements-1;
unsigned middle = 0;
while(low <= high){
middle = low + (high - low)/2;
if( inElement == array[middle]){
const T * out = &array[middle]; //problem here
return out;
}
else if(inElement < array[middle]){
high = middle -1;
}
else{
low = middle + 1;
}
}
return NULL;
}
Pointers and references were always problem for me, i read similar topics bout this with vectors and still cant understand it.
The rest of my class:
#include <iostream>
#include "Fractions.cpp"
using namespace std;
template<class T,unsigned n>
class SortedArray {
T * array;
unsigned length;
unsigned numberOfElements;
T element;
unsigned position;
public:
SortedArray() {
length = n;
array = new T[n];
numberOfElements = 0;
position = 0;
}
bool first(){
if(numberOfElements >= 1){
element = array[0];
position = 0;
return true;
}
return false;
}
bool next(){
if(position+1 < numberofElements){
position++;
element = array[position];
return true;
}
return false;
}
const T & aktual(){
return element;
}
SortedArray & operator << (const T &element){
if(numberOfElements == length || search(element) == NULL){return (*this);}
if(numberOfElements == length){return (*this);}
int i = numberOfElements;
for (; i > 0 && array[i-1] > element; i--)
{
array[i] = array[i-1];
}
array[i] = element;
numberOfElements++;
return (*this);
}
operator unsigned () const{
return numberOfElements;
}
const T *search(const T &inElement){
//this is the function causing problems
}
~SortedArray() {
delete [] array;
array = NULL;
}
};
int main()
{
SortedArray<Fractions,20> pz;
typedef Fractions Z;
pz << Z(1,3) << Z(3,5) << Z(7,4) << Z(3,4) << Z(2,3) << Z(7,2)
<< Z(5,4) << Z(1,4) << Z(6,7) << Z(4,3) << Z(2,3);
cout << "\nNumber of elements : " << pz.operator unsigned() << endl;
return 0;
}
Upvotes: 0
Views: 134
Reputation: 110146
Your function fails when numberOfElements
is 0. You have the line:
unsigned high = numberOfElements-1;
When numberOfElements
is 0, high
will receive the value -1
casted to unsigned int
, which is a very large number. This will cause access to the array beyond its end, which is undefined behavior and often will crash.
As for your question about the return
statement, what you have now is correct.
Upvotes: 2