Char* help - "reversing string"

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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.
Here is a hint for reversing:

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`
Last edited on
Thanks LB and Smac.

LB - I can't use that since I have to write the code myself, but that will be great in the future

Smac89 - I'm not sure how to implement that into the code? I will replace |s| with strlen(userInput) but thats all I can think of.
- create a new char * that will point to the beginning of the string and create another what will point to the last character in the string

- move both pointers towards the center and use the swap method from algorithm library to swap each letter the pointers are pointing to.

- repeat step 2 until all letters have been swapped
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?
if you know the size then you can do *(mystring + position ) or mystring[position] and work from the back to the start.
Topic archived. No new replies allowed.