entering characters into a string pointer
Hi all.
1. The debugger shows that the characters are entered into the word pointer, and when a punctuation or space character is encountered, I terminate the string with a '\0'. But when I use puts to print the string, garbage is printed. Why is this?
2. Also, if I don't allocate memory for word the compiler gives a warning about it being used uninitialised. But I didn't allocate memory for the array of pointers(words), and the compiler didn't give any warnings. Whats the difference between a pointer and an array of pointers?
Thanks in advance.
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;
while((ch = string[string_ctr]) != '\0')
{
word = malloc(WORD_SIZE * sizeof(char));
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';
puts(word);
words[word_ctr] = word;
string_ctr++;
word_ctr++;
word_buffer = 0;
free(word);
}
}
printf("\n");
for(ctr = 0; ctr < word_ctr; ctr++)
puts((words[ctr]));
return 0;
}