Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- char* reverseWords(char *s) {
- char** words = NULL;
- int word_count = 0;
- /*Create an array of all the words that appear in the string*/
- const char *delim = " ";
- char *token;
- token = strtok(s, delim);
- while(token != NULL){
- word_count++;
- words = realloc(words, word_count * sizeof(char*));
- if(words == NULL){
- printf("malloc failedn");
- exit(0);
- }
- words[word_count - 1] = strdup(token);
- token = strtok(NULL, delim);
- }
- /*Traverse the list backwards and check the words*/
- int count = word_count;
- char *return_string = malloc(strlen(s) + 1);
- if(return_string == NULL){
- printf("malloc failedn");
- exit(0);
- }
- int offset = 0;
- while(count > 0){
- memcpy((char*)return_string + offset, words[count - 1], strlen(words[count - 1]));
- free(words[count - 1]);
- offset += strlen(words[count - 1]);
- if(count != 1){
- return_string[offset] = ' ';
- offset++;
- }
- else {
- return_string[offset] = '