Append c-style string to my String class

Hi.

I've my GString class that accepts a c style string as parameter:

1
2
3
4
5
6
7
8
class GString
{
	private:
		char* mainString;
		int size;
        public:
                int Size() const { return size; }		// returns the size EXCLUDING the \0 NULL character
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
// CONSTRUCTOR
GString(const char* CstyleString)
{
	// +1 for the NULL character at the end (/0)
	size = strlen(CstyleString);
	mainString = new char[size+1];

	int i = 0;
	// -1 because we want to set the NULL character AFTER the copy of the character from one vector to another
	for (i = 0; i < size; i++)
		mainString[i] = CstyleString[i];

	mainString[i] = '\0';
}


And this is the append function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
GString& Append(const char* toAdd)
{
	const int finalSize = size + strlen(toAdd);

	char* finale = new char[finalSize];

	// Insert the original string characters (hell)
	int j = 0;
	for (j = 0; j < size; j++)
	{
		finale[j] = mainString[j];
	}

	// And now insert the characters of the string to append (o)
	int k = j;
	for (int i = 0; i < strlen(toAdd); k++, i++)
	{
		finale[k] = toAdd[i];
	}

	finale[k] = '\0';

	return GString(finale);
}



This is the main:

1
2
3
4
5
6
7
8
9
10
11
12
int main()
{	
	GString my = "hell";
	char* p = "o";

	my = my.Append(p);

	cout << my;

	_getch();
	return 0;
}



The cout should print "hello", instead... it prints "hell".

The appens function doesn't work!
Last edited on
The appens function doesn't work!

That's correct. Might be related to you not allocating enough memory within the function and the accompanying undefined behavior.

Do you really want to return a reference to a temporary?
hmmm, couldn't you convert your normal string to a c string using .c_str and append then?
I updated the main function.

Now I assign the result of the append function to my; then I print my (that should be the end result).

But now I get a ACCESS VIOLATION READING LOCATION
Probably because you're now using that invalid reference I asked about a little earlier.
Nice :) thanks!
Glad to see someone making their own string class. Bravo! I use my own also. Its a good way to learn C++!
Not helpful in anyway, but I like your class name..
Topic archived. No new replies allowed.