Questa è una possibile soluzione didattica, vedi se fa quello che vuoi te...
codice:// Reverse sentence #include <stdio.h> #include <stdlib.h> #include <string.h> // Prints in reverse order the words of a sentence void reverse( char *sentence, const char delimiter ); int main( int argc, char *argv[] ) { if( argc != 2 ) { printf( "Usage: %s <sentence>\n", argv[0] ); exit(EXIT_FAILURE); } reverse(argv[1], ' '); return 0; } // Prints in reverse order the words of a sentence void reverse( char *sentence, const char delimiter ) { unsigned n; // Numbers of delimiters in the sentence char *charPtr = NULL; // Calculates the number of delimiters charPtr = strchr(sentence, delimiter); for( n = 0; charPtr != NULL; ++n, charPtr = strchr(charPtr+1, delimiter) ); // More words... if( n ) { // Allocates the word's array of pointers char **rWords = (char **) malloc( (n+1) * sizeof(char *) ); if( rWords != NULL ) { int i = 0; // The brutal pointers for( rWords[i] = strtok(sentence, &delimiter); i != n; rWords[i] = strtok(NULL, &delimiter) ) ++i; // Prints words in reverse order for( i = n; i >= 0; --i) printf( "%s\n", rWords[i] ); // Relase rWords free(rWords); } } // One word else printf("%s\n", sentence); }

Rispondi quotando