Working through some programming interview challenges I found online, I had to write an algorithm to reverse a const char * and return a pointer to a new char *. I think I have it, but to make it work properly I had to do some wonky stuff - basically having to account for the null-terminating character myself. Somehow I feel this is wrong, but I'm stumped, and I was wondering if someone could help me out:
char * reverse(const char * str)
{
int length = strlen(str);
char * reversed_string = new char[length+1];
for(int i = 0; i < length; ++i)
{
reversed_string[i] = str[(length-1) - i];
}
//need to null terminate the string
reversed_string[length] = '\0';
return reversed_string;
}
int main(int argc, char * argv[])
{
char * rev_str = reverse("Testing");
cout << "Your string reversed is this: " << rev_str << endl;
delete rev_str;
rev_str = 0;
return 0;
}