這是我的程序代碼,用於統計標準輸入中的單詞並將它們整理爲直方圖。有一個名爲wordArray的結構數組,我不知道如何爲它分配內存。我的理解可能有其他的問題,我還沒有使用的變量,但我只是想知道如何解決我一直在編譯時得到的錯誤:爲結構數組分配內存
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));
^
來源:
#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++;
}
}
}
你喜歡的全局變量,是吧? – 2015-03-31 00:56:43