Thanks Barney. I've figured that the problem was in the location of the malloc. That is fixed, but I can't figure out why I am still getting garbage printed in the for loop.
Code:
// wordcount.c - count words.
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#define WORDS_MAX 20
#define WORD_SIZE 50
int main( void )
{
char *string = "How now brown cow. A cow has four brown legs.";
char *words[WORDS_MAX];
char *word;
int ch, ctr, string_ctr = 0, word_ctr = 0, word_buffer = 0;
if((word = malloc(WORD_SIZE * sizeof(char))) == NULL)
perror("Error allocating memmory");
while((ch = string[string_ctr]) != '\0')
{
if((ispunct(ch) == 0) && (isspace(ch) == 0)) // ch is not a punctuation and not a white space
{
word[word_buffer] = ch;
word_buffer++;
string_ctr++;
}
else
{
word[word_buffer] = '\0';
words[word_ctr] = word;
printf("%s ", words[word_ctr]);
string_ctr++;
word_ctr++;
word_buffer = 0;
free(word);
if((word = malloc(WORD_SIZE * sizeof(char))) == NULL)
perror("Error allocating memmory");
}
}
free(word);
printf("\n");
for(ctr = 0; ctr < word_ctr; ctr++)
printf("%s ", words[ctr]);
return 0;
}