Pointers to swap locations in char array

Using pointers to revers the char array running into a problem with even numbered arrays. Any help would be greatly appreciated.




#include <iostream>
#include <string>
using namespace std;
void reverse(char* first,char* last){
char temp;
while(first!=last)
{
char tmp = *first;
*first = *last;
*last = tmp;
++first;
--last;
}


}
int main()
{
char input[100]; // inputReverse[100]; //user input, 100 characters should be sufficient
cout << "Please enter a word or characters (no spaces) : "<<endl;
cin >> input;
cout<<" You entered : "<<input<<endl;
char* first = input;
char* last = input + strlen(input)-1;
reverse(first,last);
cout << "The reverse is : " << input;
cout << endl;


system("PAUSE");
return 0;
}
Last edited on
Do you understand the problem? When there's an even number of elements first is never equal to last as first is incremented AND last is decremented so they skip over each other in the middle. Changing
while (first != last) to
while (first < last) will solve this.

Please use code tags in the future
Last edited on
The problem is 'while(first!=last)' - think about the case where you pass in, say 'tamper'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
iteration 1)
tamper
^    ^
f    l

iteration 2)
rampet
 ^  ^
 f  l

iteration 3)
rempat
  ^^
  fl

iteration 4)
repmat
  ^^
  lf

now you are using (first!=last) as your end condition. clearly you are finished at this point, but first does not equal last. You need a different end condition (which should, at this point, be easy to see)
Last edited on
Topic archived. No new replies allowed.