这是我的程序代码,该程序对标准输入中的单词进行计数并将它们整理成直方图。有一个称为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++;
        }
    }

}

最佳答案

要为nWords元素数组分配空间,请使用

wordArray = malloc(nWords * sizeof(*WordInfo));

关于c - 为结构数组分配内存,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29358769/

10-11 23:04
查看更多