11
Inverser le contenu d'une chaîne de caractères
- #include <stdio.h>
- #include <string.h>
- char *reverse( char *s ) {
- char *p, *q;
- for ( p = s, q = s+strlen(s)-1; q > p; p++, q-- ) {
- char c = *p;
- *p = *q;
- *q = c;
- }
- return s;
- }
- void test( char *s )
- {
- /* printing s and reverse( s ) in one statement calls reverse first! */
- printf( "[%s]", s );
- printf( "<->" );
- printf( "[%s]", reverse( s ));
- printf( "\n" );
- }
- main( ) {
- /* don't use char * (read-only) with cl /GF */
- char s1[] = "123";
- char s2[] = "12";
- char s3[] = "";
- char *s4 = "abcdef";
- test( s1 );
- test( s2 );
- test( s3 );
- test( s4 ); /* segmentation fault */
- }
$ gcc -o reverse reverse.c
$ ./reverse
[123]<->[321]
[12]<->[21]
[]<->[]
Erreur de segmentation
Commentaires