I'm trying to do a pretty basic array of strings that is dynamically growable for adding on new words to certain indexes. I need it in this basic format (i.e. can't use anything from the STL). Just a couple things to note: I'm not worried about overwriting old words, and the unused indexes of the new string arrays are fine just being empty strings.
I know my problem (seg. fault) is in my set function, but I don't know why it's happening. I'm trying to create a new, larger array of strings with the required size, populate it with the previous words, and then assign it to my class string array (after deleting the old data), and then putting in the new word at the new index.
There may be more mistakes, so feel free to be critical of any and/or all of them.
Thanks.
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
class GA
{
public:
GA();
GA(const GA & other);
~GA();
GA & operator=(const GA & rhs);
string get(unsigned index) const;
GA & set(unsigned index, const string & s);
private:
string * word;
int size;
};
void die(const string & msg);
int main()
{
GA w;
w.set(2, "Index Two");
w.set(6, "Index Six");
cout << w.get(2);
cout << endl;
cout << w.get(3);
}
GA::GA()
{
word = NULL;
size = 0;
}
GA::GA(const GA & other)
{
try
{
word = new string[other.size];
}
catch(const bad_alloc &){ die("Alloc. Failure");
}
size = other.size;
for (int i = 0; i < other.size; i++)
word[i] = other.word[i];
}
GA::~GA()
{
delete [] word;
}
GA & GA::operator=(const GA & rhs)
{
if (this != &rhs)
{
delete [] word;
try
{
word = new string[rhs.size];
}
catch(const bad_alloc &)
{
die("Alloc. Failure");
}
for (int i = 0; i < rhs.size; i++)
word[i] = rhs.word[i];
}
return *this;
}
string GA::get(unsigned index) const
{
return word[index];
}
GA & GA::set(unsigned index, const string & s)
{
if (index > size) // need more memory, creating another string array.
{
int newSize = index;
string * newWord = NULL;
try
{
newWord = new string[newSize];
}
catch(const bad_alloc &)
{
die("Alloc. Failure");
}
for (int i = 0; i < newSize; i++)
{
newWord[i] = word[i];
}
delete [] word;
word = newWord;
size = newSize;
}
word[index] = s;
return *this;
}
void die(const string & msg)
{
cerr << "Fatal Error: " << msg << endl;
exit(EXIT_FAILURE);
}
std::coutandstd::string:Dgetas well.