tags:

views:

239

answers:

1

Not counting the function signature (just the body) can anybody produce C code shorter than this function that will reverse a string and return the result as a pointer to the reversed string.. (not using a string reverse library function either)?

char * reverse_str(char * s)
{
   char c,*f=s,*p=s;while(*p)p++;while(--p>s){c=*p;*p=*s;*s++=c;}return f;
}
+2  A: 

not much longer, but it works.

#include <string.h>

/* precondition: s!=const && s!=NULL && *s!='\0' */
char *mystrrev(char *s)
{
  char *a=s,*e=s+strlen(s)-1;
  while( a<e )
  {
    char c=*a;
    *a++=*e;
    *e--=c;
  }
  return s;
}
segmentation fault ?
Kedar
where, when preconditions are ok?
@Kedar: segmentation fault probably occured because you passed it a string literal or constant, which you shouldn't have done since it takes a `char *` and not a `const char *`. You may have even gotten a compiler warning telling you not to do that.
nategoose