I have an assignment where I have to take Hello World! as a char array and pass it to a function that will reverse it. I'm having a hard time understanding pointers and so any help or links would be helpful. I've read a few pages on here but still don't understand it. Basically I have to reverse the char array with pointers only, I can't have any brackets in my function. Here is what I have:
void Test()
{
// declare a C-String to reverse
char myString[] = "Hello world!";
// call the reverser function
Reverse(myString);
// output the result
cout << myString << endl;
system("PAUSE");
}
char* Reverse(char* userInput)
{
while (*userInput)
{
userInput++;
}
char* lastChar = userInput--;
cout << "Char: " << userInput << endl; // used to make sure I found the last char.
return 0; //will have to return a full char array to output
}
I can find the last char, but I don't know how to move it to slot one or how to find the second to last char once I do move it.
reversing simply means switching position of opposite characters i.e. after reversing a string, first character is now last, second is now second last, third is third last, etc. So to reverse is equivalent to swapping all opposite characters in the string
So with this, the algorithm complexity for reversing a string is simply O(|s|/2) where |s| represents the length of string `s`
Thanks, Smac. I've been finding the last char by just doing userInput++. Is there an easier way to set a char pointer variable for the beginning and end chars?