This is my code for a program that counts the words in the standard input and orangizes them into a histogram. There is an array of structs called wordArray, and I don't know exactly how to allocate memory for it. I understand there are probably other problems and variables that I haven't used yet, but I just want to know how to fix the error I keep getting at compile time:
countwords.c: In function 'main':
countwords.c:70:22: error: incompatible types when assigning to type 'WordInfo'
from type 'void *'
wordArray[nWords] = malloc(sizeof(WordInfo));
^
Source:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct WordInfo {
char * word;
int count;
};
typedef struct WordInfo WordInfo;
int maxWords;
int nWords = 0;
WordInfo* wordArray;
#define MAXWORD 100
int wordLength;
char word[MAXWORD];
FILE * fd;
int charCount;
int wordPos;
void toLower(char *s) {
int slen = 0;
while (*(s + slen) != '\0') {
if (*(s + slen) < 'a') *(s + slen) += 'a' - 'A';
slen++;
}
}
// It returns the next word from stdin.
// If there are no more more words it returns NULL.
static char * nextword() {
char * word = (char*)malloc(1000*sizeof(char));
char c = getchar();
int wordlen = 0;
while (c >= 'a' && c <= 'z') {
*(word + wordlen) = c;
wordlen++;
c = getchar();
}
if (wordlen == 0) return NULL;
return word;
}
int main(int argc, char **argv) {
if (argc < 2) {
printf("Usage: countwords filename\n");
exit(1);
}
char * filename = argv[1];
int wordfound = 0;
fd = fopen(filename, "r");
char * next = nextword();
while (next != NULL) {
int i;
for (i = 0; i < nWords; i++) {
if (strcmp((wordArray[i]).word, next)) {
wordArray[i].count++;
wordfound = 1;
break;
}
}
if (!wordfound) {
wordArray[nWords] = malloc(sizeof(WordInfo));
strcpy(next, wordArray[nWords].word);
wordArray[nWords].count++;
nWords++;
}
}
}