Click here to Skip to main content
15,889,403 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
void eatSpaces(const char arr[])
{
	char* str = new char[];
	size_t strPosition{}, arrPosition{};
	while (arr[arrPosition] != '\0')
	{
		if (arr[arrPosition] != ' ')
			str[strPosition++] = arr[arrPosition];

		arrPosition++;
	}
	cout << str << endl;
}

void main()
{
	char str[]{"hello world"};
	eatSpaces(str);
}


every time I run this program it shows 2 absurd characters at the end of the str[]. They are like some randomly generated characters..
For the first time, it displays "helloworldφ8"
and then, "helloworld.C"
after that, "helloworld├b"

It isn't same always.. I just want to know why this happens.. Not another way to remove spaces without this problem.. Thanks..
Posted

1 solution

The problem is that you copy the characters from arr to str, and stop (correctly) when the null character is reached. However, you forget to add a null character at the end of the newly created string. It should be:
C++
while (arr[arrPosition] != '\0')
{
    if (arr[arrPosition] != ' ')
        str[strPosition++] = arr[arrPosition];

    arrPosition++;
}
str[strPosition] = '\0';  // null terminate the new string


By the way, what compiler are you using, as this will not compile under Microsoft's C++ compiler, owing to the strange syntax on some statments?
 
Share this answer
 
Comments
M­­ar­­­­k 25-May-14 9:03am    
Im using the compiler that came with visual studio 2013
Richard MacCutchan 25-May-14 9:30am    
Thanks, I must learn the new syntax.

You also have a potential bug in this code. When you create the second array with the line
char* str = new char[];
it returns you a pointer to a default sized buffer. According to my tests this buffer is 64 bytes (characters) long. So if you write more than that number of characters into it you will corrupt the heap and see strange results.
M­­ar­­­­k 25-May-14 9:49am    
oh.. Thanks. Didn't know that..
Richard MacCutchan 25-May-14 9:51am    
Nor did I, and the documentation is not very clear.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900