Advertisement
Guest User

Untitled

a guest
Aug 28th, 2015
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. char* reverseWords(char *s) {
  2. char** words = NULL;
  3. int word_count = 0;
  4.  
  5. /*Create an array of all the words that appear in the string*/
  6. const char *delim = " ";
  7. char *token;
  8. token = strtok(s, delim);
  9. while(token != NULL){
  10. word_count++;
  11. words = realloc(words, word_count * sizeof(char*));
  12. if(words == NULL){
  13. printf("malloc failedn");
  14. exit(0);
  15. }
  16. words[word_count - 1] = strdup(token);
  17. token = strtok(NULL, delim);
  18. }
  19.  
  20. /*Traverse the list backwards and check the words*/
  21. int count = word_count;
  22. char *return_string = malloc(strlen(s) + 1);
  23. if(return_string == NULL){
  24. printf("malloc failedn");
  25. exit(0);
  26. }
  27. int offset = 0;
  28. while(count > 0){
  29. memcpy((char*)return_string + offset, words[count - 1], strlen(words[count - 1]));
  30. free(words[count - 1]);
  31. offset += strlen(words[count - 1]);
  32. if(count != 1){
  33. return_string[offset] = ' ';
  34. offset++;
  35. }
  36. else {
  37. return_string[offset] = '';
  38. }
  39. count--;
  40. }
  41. printf("%sn",return_string);
  42. free(words);
  43. return return_string;
  44. }
  45.  
  46. int main(){
  47. char *string = malloc(1000);
  48. if(string == NULL){
  49. printf("malloc failedn");
  50. exit(0);
  51. }
  52. fgets(string, 1000, stdin);
  53. string[strlen(string)] = '';
  54. reverseWords(string);
  55. return 0;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement