I want to write a function that splits a string into words (strings with no whitespace), returning a (dynamically allocated) array of pointers to (dynamically allocated) copies of the words in the string.
Code:
#include <stdio.h>
#include <stdlib.h>
void readText(char *s)
{
s = (char*)malloc(256*sizeof(char));
if(s == NULL)
{
fprintf(stderr, "Memory could not be allocated.");
exit(-1);
}
while(fgets(s, sizeof(s)/sizeof(s[0]), stdin))
{
char *ptr = strchr(s, '\n');
if(ptr)
{
*ptr = '\0';
}
char *word = strtok(s, " ");
while(word != NULL)
{
printf("Word : %s\n", word);
word = strtok(NULL, " ");
}
}
free(s);
}
int main()
{
char *s;
readText(s);
return 0;
}
I wrote this so far and I wanted to see if the function is getting each word from the input correctly and it's not.
Input:
anna has many red delicious apples
Output:
Word : anna
Word : ha
Word : s
Word : many
Word : red
Word : del
Word : icious
Word : apples
I have no idea why this is happening, my best guess would be that the second argument in fgets is wrong, I tried a lot of different things but nothing is working, I removed the trailing newline but no improvement.