I have an append function part of a string class I am working on, and something very strange happens upon usage. When I print out the appended string inside the function and then also in main
, it works. But when I comment out the printing part inside the function and just leave the print in main
, the output is some random character. Here is the code:
String.cpp:
void String::append(const String buf)
{
char c[99];
for (auto i = 0; i < this->length(); ++i) {
c[i] = this->cstr()[i];
}
for (auto i = this->length(); i < (this->length() + buf.length() + 1); ++i) {
c[i] = buf.cstr()[i - this->length()];
}
*this = c;
printf("%s\n", *this); // if I comment this line out then the append function doesn't work properly
}
Main:
int main()
{
String a = "Hello";
String b = "Hi";
a.append(b);
printf("%s\n", a);
}
When both print functions are used, the output is this:
When only the print function in main is used:
What might be causing this? Thanks.
Edit:
Assignment operator:
String &String::operator=(char* buf) {
_buffer = buf;
return *this;
}
Constructor:
String::String(char* buf) : _buffer(buf), _length(0) {
setLength();
}