#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int ret_words(char **words){ //double pointer argument
char str[50];
char *temp = malloc(1); //first allocation required
int count = 0;
if(temp == NULL){ //allocation error
return -1;
}
do{
temp = realloc(temp, strlen(str) + strlen(temp) + 2); //reallocate space at every scan
if(temp == NULL){
return -1;
}
count++;
} while (scanf("%49s", str) == 1 && strcat(temp, str) //scan str and append to temp
&& getchar() != '\n' && strcat(temp, " ")); //with spaces between
*words = temp; //assign temp to words
return count; //return word count
}
int main()
{
int ret;
char *words;
puts("Enter the string");
putchar('>');
ret = ret_words(&words); //returned number of words on success, -1 on error
printf("Inputed string: %s\nNumber of words: %d", words, ret); //test print
}