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"
constint 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;
}
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: