Link to home
Start Free TrialLog in
Avatar of chunich
chunich

asked on

Reverse a string

Why is the reverse function giving me error while running it?
It is right at the assignment *p = *len statement.

void reverse(char *str) {
      char *len = &str[strlen(str)-1];
      char tmp;
      for (char* p = str; p < len; p++, len--) {
            tmp = *p;
            *p = *len;
            *len = tmp;
      }
}

int main(int argc, char* argv[])
{
      reverse("barbeque");
      return 0;
}
SOLUTION
Avatar of brettmjohnson
brettmjohnson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jhance
jhance

By the way, while it's not a part of the std. "C" RTL, many implementation (in fact MOST) have an implementation of a string reversal function.  In MS Visual C it's _strrev().  Most others use strrev() or similar.  In my opinion it's best NOT to re-invent the wheel if you can help it.
jhance,

The "Reverse a string" problem is a very common academic assignment, used to teach the use of pointers, arrays, and C strings.  The students are discouraged from using the library routine to accomplish the task, since they really would not learn anything.
They also don't learn much by getting their homework done by experts here.  But that's another story...
//They also don't learn much by getting their homework done by experts here.  But that's another story...

This is not the case in this thread, the algorithm proposed by the student is correct but he has only a problem of memory allocation and need help just at this point  so 90% of the job is done by him self and not by experts and I think that's correct .

B.T
Avatar of chunich

ASKER

Thank you guys so much.