So I'm working on a homework assignment where, after having written our own versions of the std::string class with some basic functions using a dynamic array of chars, we're supposed to translate that to a linked list. Everything was functional (though likely not as efficient as possible), but I've hit a snag. The lowest += overload function, where you'd just be adding a single char to the end of a string object, seems to work fine when I test it. The second one, where you'd be adding an array of chars to a string object, does not. Trying to use it causes a runtime error. Since the highest += overload function relies on the second one, that also isn't working.
I think the problem is related to the line:
headPtr += addend[index];
But I'm not sure what to use in place of headPtr if that is in fact the issue. Here's the code:
HEADER:
#ifndef STRING2_H
#define STRING2_H
#include <cstring>
namespace string2
{
class string
{
private:
struct stringList
{
char character;
stringList* link;
};
stringList* headPtr;
public:
// CONSTRUCTORS AND DESTRUCTOR
string() { headPtr = NULL; };
string(const stringList* sourcePtr);
~string();
// CONSTANT MEMBER FUNCTIONS
char getChar(const size_t position) const;
size_t length() const;
char operator [ ] (size_t position) const;
// MODIFICATION MEMBER FUNCTIONS
void operator += (const string& addend);
void operator += (const char addend[]);
void operator += (char addend);
};
}
#endif
RELEVANT .CPP FUNCTION DEFINITIONS:
void string::operator += (const string& addend)
{
for (int i = 0; i < addend.length(); i++)
headPtr += addend[i];
}
void string::operator += (const char addend[])
{
if (addend[0] == NULL)
return;
for (int index = 0; index < (sizeof(addend) / sizeof(addend[0])); index++)
headPtr += addend[index];
}
void string::operator += (char addend)
{
stringList *indexPtr = headPtr;
if (headPtr == NULL)
{
headPtr = new stringList;
headPtr->character = addend;
headPtr->link = NULL;
return;
}
while (indexPtr->link != NULL)
indexPtr = indexPtr->link;
indexPtr->link = new stringList;
indexPtr->link->character = addend;
indexPtr->link->link = NULL;
}
Help is appreciated!