I am stuck please help , i get a segmentation fault
this is something you can debug if you want to help me :
debug.h
```
#ifndef DEBUG_H_
#define DEBUG_H_
template <class T>
class SortedList
{
T** data;
int size;
int max_size;
void expand();
static const int EXPAND_RATE=2;
static const int INITIAL_SIZE=10;
public:
SortedList();
void insert(const T&);
};
template <class T>
SortedList<T>::SortedList():data(new T*[INITIAL_SIZE]),size(0),max_size(INITIAL_SIZE){}
template<class T>
void SortedList<T>::expand()
{
int new_size = max_size * EXPAND_RATE;
T** new_data = new T * [new_size];
for (int i = 0; i < size; ++i)
{
T Item(*(data[i]));
T* ptr = &Item;
new_data[i] = ptr;
}
delete[] data;
data = new_data;
max_size = new_size;
}
template <class T>
void SortedList<T>::insert(const T& object)
{
if(size>=max_size)
{
expand();
}
int index=0;
for(int i=0;i<size;i++)
{
T item=*data[i];
if(item<object)
{
continue;
}
index=i;
break;
}
size++;
for (int i = size-1; i >index; i--)
{
data[i]=data[i-1];
}
T Item(object);
T* ptr = &Item;
data[index] = ptr;
}
#endif
```
debug.c
#include "debug.h"
#include <string>
using std::string;
int main()
{
SortedList<string> lst1 = SortedList<string>();
lst1.insert("Charlie");
lst1.insert("Bob");
return 0;
}
please please help.. I have been trying for hours
PS: I made data an array of pointers so that we could use the list even with a class that doesn't have a T()
if there is anything I wrote wrong and you want me to edit you can tell me in the comments below, thanks in advance!!
What I have tried:
I tried to do this in the insert function:
template <class T>
void SortedList<T>::insert(const T& object)
{
if(size>=max_size)
{
expand();
}
int index=0;
for(int i=0;i<size;i++)
{
if(*data[i] <object)
{
continue;
}
std::cout << *data[i];
index=i;
break;
}
size++;
for (int i = size-1; i >index; i--)
{
data[i]=data[i-1];
}
T Item(object);
data[index] = &Item;
std::cout << *data[index];
}
when I did this I didn't get a segmentation fault but when I try to get to the
*data[i]
from the out side or anywhere else, it gives me nothing as if nothing was stored inside