4

Reverse the contents of a string of characters

  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. char *reverse( char *s ) {
  5.     char *p, *q;
  6.  
  7.     for ( p = s, q = s+strlen(s)-1; q > p; p++, q-- ) {
  8.         char c = *p;
  9.         *p = *q;
  10.         *q = c;
  11.     }
  12.     return s;
  13. }
  14.  
  15. void test( char *s )
  16. {
  17.     /* printing s and reverse( s ) in one statement calls reverse first! */
  18.     printf( "[%s]", s );
  19.     printf( "<->" );
  20.     printf( "[%s]", reverse( s ));
  21.     printf( "\n" );
  22. }
  23.  
  24. main( ) {
  25.     /* don't use char * (read-only) with cl /GF */
  26.     char s1[] = "123";
  27.     char s2[] = "12";
  28.     char s3[] = "";
  29.     char *s4 = "abcdef";
  30.  
  31.     test( s1 );
  32.     test( s2 );
  33.     test( s3 );
  34.     test( s4 ); /* segmentation fault */
  35. }
$ gcc -o reverse reverse.c
$ ./reverse
[123]<->[321]
[12]<->[21]
[]<->[]
Segmentation fault

Comments

Your comment:
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip help 2000

Enter a maximum of 2000 characters.
Improve the presentation of your text with the following formatting tags:
[p]paragraph[/p], [b]bold[/b], [i]italics[/i], [u]underline[/u], [s]strike[/s], [quote]citation[/quote], [pre]as is[/pre], [br]line break,
[url]http://www.izend.org[/url], [url=http://www.izend.org]site[/url], [email]izend@izend.org[/email], [email=izend@izend.org]izend[/email],
[code]command[/code], [code=language]source code in c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].