I wrote a program to reverse string where the string is a character array. The program is :
#include<iostream>
void rev(char *str)
{
char *end;
end = str;// end will now point to the same address of str
// now we need to incremet the end pointer upto it encounter null
if(str)// this checks if the string is present or not
{
while(*end)
++end;
--end;// set one character back, since last character is null
// swap characters from start of string with the end of the string
// until the pointers meet in middle.
while(str < end)
{
char temp = *str;
*str++ = *end;
*end-- = temp;
}
}
std::cout<<"\n The reversed string is : \n";
std::cout<<str<<std::endl;
}
int main()
{
char str[500];
std::cout<<"\n Enter the string : ";
std::cin.getline(str, sizeof(str));
rev(str);
return 0;
}
One output instance is :
Enter the string : asdfgh
The reversed string is :
dsa
I want to solve this problem inplace and using character array.
There are many solutions available on internet. I have seen them. But I want to know where I'm going wrong with this implementation. If there is some extra increment in str. I want to know how to correct it.