Issue with cout for a char array. Appearance of weird character

I used the following code to reverse a char array (string). String itself is reversed but at the end of the string there appears an unusual character. This character repeats as many times as the length of array.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void reverseChar(char String[])
{
	//input is mystr
	//char mystr[] = "HelloWorld"
	const int x = countChar(String);
	//cout << "Entered reverseChar: " << x << endl;
	char newstring[10];
	for (int y = 0; y < x; y++)
	{
		//cout << "Itteration number: " << y + 1 << endl;
		newstring[y] = String[x - y-1];
		//cout << newstring[y] << endl;
	}
	cout << "Reversed string: " << newstring << endl;
}
Works fine for me, if I replace countChar() with strlen(). Could we see your countChar() function? It is probably giving you a number too large.
you probably didn't zero terminated `newstring'
My countChar(char string[]) is:
1
2
3
4
5
6
7
8
9
int countChar(char String[])
{
	int length = 0;
	while (String[length] != '\0')
	{
		length++;
	}
	return length;
}
Hey Viraldude your problem is very simple.........

you havn't used string terminator so the the emty indexes will show garbage values.................


just add this......
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void reverseChar(char String[])
{
	//input is mystr
	//char mystr[] = "HelloWorld"
	const int x = countChar(String);
	//cout << "Entered reverseChar: " << x << endl;
	char newstring[10];
	for (int y = 0; y < x; y++)
	{
		//cout << "Itteration number: " << y + 1 << endl;
		newstring[y] = String[x - y-1];
		//cout << newstring[y] << endl;
	}
        newstring[y]='\0';
	cout << "Reversed string: " << newstring << endl;
}
That worked. Thank you very much!
Um...
In your example, you are having a buffer overflow, which will occasionally cause errors. This is because you are declaring newstring as a string of size 10. If you passed, for example, "HelloWorld" (i.e. 10 characters), and added a null terminator, you would now have an array of size 10 holding data of size 11.

You probably want to dynamically allocate newstring to be 1 + the size of the string, like so:
1
2
3
4
5
6
int x =countChar(String);
char *newstring = new char[x + 1];
// ...
newstring[y] = '\0';
cout << "Reversed string: " << newstring << endl;
delete newstring;
Topic archived. No new replies allowed.