sizeof的应用程序无效,无法完成struct wordcounter

时间:2013-12-04 06:02:39

标签: c pointers struct malloc sizeof

我正在编写一个程序来计算文本文件中单词出现的次数。这是通过使用包含单词和该单词计数的结构来完成的。我收到一个汇编我收到的错误是:

  

“sizeof应用于不完整类型struct wordcounter。”

有关如何解决此问题以及我的代码的任何输入都表示赞赏。我是c的新手,所以我也乐于接受与这个问题无关的建议。非常感谢。我的代码是:

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

#define MAXWORDS 5000
#define MAXLINE 1000
#define MAXWORDLEN 100


int count = 0;
struct wordcount *wordPtr[MAXWORDS];

typedef struct wordcount *wordcountptr;

typedef struct wordcount {
    char word[50];
    int count;
} wordcount;


main()
{

    int wordfound = 0;
    int len;
    char line[MAXLINE];
    int printcount;

    while ((len = getline(line, MAXLINE, stdin))> 0)
    {
        int i = 0;
        int j = 0;

        for( ; i<len; i++)
        {
            if(line[i] != isalnum(line[i]) && line[i] != 32)
                line[i] = 32;
            else
                line[i] = tolower(line[i]);
        }

        for( ; j<len; j++)
        {

            char currentword[MAXWORDLEN];

            if(line[j] != 32)
            {
                for(i=0; line[j] != 32; i++)
                    currentword[i] = line[j];
            }
            if(line[j] == 32)
            {
                for(i=0;i<MAXWORDS; i++)
                {
                    if(strcmp(currentword, (*wordPtr[i]).word) == 0)
                    {
                        (*wordPtr[i]).count++;
                        wordfound = 1;
                    }
                }

                if(wordfound == 0)
                {
                    wordPtr[i] = (struct wordcounter*)malloc(sizeof(struct wordcounter));
                    strcpy((*wordPtr[i]).word, currentword);
                    (*wordPtr[i]).count = 1;
                    count++;
                }
            }
            wordfound = 0;
        }
    }

    for(printcount = 0; printcount < count; printcount++)
        printf("There are %d occurances of the word %s\n", (*wordPtr[printcount]).count, (*wordPtr[printcount]).word);

    for(printcount = 0; printcount < MAXWORDS; printcount++)
    {
        free((void*)wordPtr[printcount]);
        wordPtr[printcount]= NULL;
    }
}

1 个答案:

答案 0 :(得分:2)

typedef struct wordcount {
    char word[50];
    int count;
} wordcount_t;//modify like this

wordPtr[i] = (wordcount_t*)malloc(sizeof(wordcount_t));//modify like this
相关问题