C Text Processing: Output Wrong Size
I'm writing ac program that takes a text file of words, and copies only words without capitalization or punctuation, and which are 4 or more characters long. I have tested the boolean functions int containsPunctuationOrCaps(char *word) and int longerThanThree(char *word) , and they both work. However, my main function only prints words of at least seven characters, and anything longer is truncated.
int main() {
char *currentWord = malloc(36);
int count = 0;
char *Words[3000];
FILE *fin, *fout;
fin = fopen(INFILE,"r");
if (fin==NULL) {
printf("INPUT FILE NOT FOUNDn");
return 1;
}
while(fgets(currentWord, sizeof(currentWord), fin) != NULL) {
if(!containsPunctuationOrCaps(currentWord) && longerThanThree(currentWord)) {
Words[count]=currentWord;
printf("%sn",currentWord);
count++;
}
}
fclose(fin);
}
When I change char *currentWord = malloc(36); to char currentWord[]; it doesn't read anything. How do I make this work?
You declare currentWord
as a char *
, which points to dynamically allocated memory. sizeof
is evaluated at compile-time, and evaluates to the size (in bytes) required by the type of currentWord
- in your case, the size required to store a memory address/pointer, which apparently is 8 bytes on your system. Since fgets
appends a terminating