Here is my question:
Write a function void reverse(char s[]) that reverses a character string. For example, “Harry” becomes “yrraH”.
And here is my code :
void reverse(char s[]);
int main()
{
char s [] = "Harry";
reverse(s);
cout << s << endl;
system("PAUSE");
return 0;
}
void reverse(char s[])
{
int length = strlen(s);
int c, i ,j;
for(int i=0, j=length-1 ; i<j ; i++, j--)
{
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
It works perfectly to reverse the string. However, I was asked to do it in pointer. So from what I thought, first I assign a p pointer to get the first char in string. Then I assign a q pointer to get the last char of string. The I loop thru to reverse the array. But when I tried to do this to get the last char:
char *q = strlen(s-1);
I got an error. Can somebody help me fix this using pointer?
Updated portion
if (strlen(s) > 0(
{
char* first = &s[0];
char*last = &s[strlen(s)-1];
while(first < last)
{
char temp = *first;
*first = *last;
*last = temp;
++first;
--last;
}
}