-
strrev()
is this a good version of it I found it on the internet.
Code:
char *strrev(char *s){
int i,n;
char *reverse;
for(i=0;s[i]!='\0';i++)
;
reverse=malloc(i*sizeof(char));
n=i-1;
for(i=n;i>=0;i--)
reverse[n-i]=s[i];
reverse[n+1]='\0';
return reverse;
}
-
Only truly bad thing I see is no error checking on malloc.
-
Isn't it better that the caller assigns memory and passes a pointer in? This way you're less likely to forget to free it.
-
>is this a good version of it
No, not really. It's obscure and buggy, and if at all possible you should keep memory management in the same function. That way it's easier to remember to free it.
>reverse=malloc(i*sizeof(char));
Whoever wrote this forgot about an extra spot for the '\0'. IMHO, a better way would be like so:
Code:
#include <stdio.h>
#include <stdlib.h>
char *jstrrev ( char *dst, char *src )
{
int s = 0, e;
for ( e = 0; src[e] != '\0'; e++ )
;
while ( e != 0 )
dst[s++] = src[--e];
dst[s] = '\0';
return dst;
}
int main ( void )
{
char r[5];
puts ( jstrrev ( r, "test" ) );
return 0;
}
-
Here is another variation that reverses the string in place.
Code:
#include <stdio.h>
#include <string.h>
char *mystrrev(char *s)
{
char *start = s, *t = strchr(s, '\0'); /* point to end of string */
/*
* Swap the values at the beginning (pointed to by 's') and the end
* (pointed to by 't'); 's' and 't' meet in the middle.
*/
for ( --t/* skip terminating null character */; s < t; ++s, --t )
{
/* Just your run-of-the-mill swap here. */
char temp = *s;
*s = *t;
*t = temp;
}
return start;
}
int main(void)
{
char text[] = "Hello world";
puts(text);
puts(mystrrev(text));
return 0;
}
/* my output
Hello world
dlrow olleH
*/
-
Thanx I knew there would be a way to do it without malloc:)