char * reverse_string(const char *s1)
{
int count = 0;
char *output;
char *o;
while(*s1 != '\0')
s1++;
s1--;
output = new char[strlen(s1)];
o = output;
while(*s1)
*output++ = *s1--;
if(*s1 == '\0')
cout<<"yes";
return o;
}
int main()
{
const char *s1 = "hello world";
char *result;
result = reverse_string(s1);
cout<<result;
}
This is a way of implementing string reverse. I know the code uses extra space and strlen()
, which is not optimal.
But, my question is, when I decrement the s1
pointer one location from the beginning of the input string, it has '\0'
as its value. I do not understand how that could be feasible? For testing, I am printing an "yes" (at the end of function strrevImp()
).
Could someone point out if I am lost anywhere here?