I need to read words from a text file, build a structure to store the word and its occurrence. From what I was told from my TA, I need to read words, determine its size (how many chars) and allocate memory for its size. Then I need to build an array of pointers and point the pointers to structures that stores words.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct word {
int count; // counter to use the word's occurrence
char wrd[0];
}*wordptr[50];
int main()
{
int position = 0; // increment for each word found, till 50
FILE *myfile;
if ((myfile = fopen("wordlist", "r")) == NULL) {
printf("\n Error:Can't open file \n ");
exit(0);
}
char temp[99]; // temp char array to store words read from file
while (fscanf(myfile, "%s", temp) != EOF) {
wordptr[position] = (struct word *) malloc(sizeof(struct word));
printf("temp is: %s\n", temp);
strcpy(wordptr[position]->wrd, temp);
wordptr[position]->count = 1; // assign 1 for now
printf("wordptr[%d].wrd: %s\n", position, wordptr[position]->wrd);
position++;
if (position == 50) {
break;
}
}
int i;
for (i = 0; i < 50; i++){
// see if I'm doing it right
printf("at %d, count:%d, wrd:%s\n", i, wordptr[i]->count, wordptr[i]->wrd);
}
return 0;
}
Everything seems to be working like I want, but am I doing anything wrong? Especially in declaring pointers and arrays of char. I'm kinda confused with pointers and them pointing to structures. So does the array of pointer actually stores all the values of the structure?