sizeof的应用程序无效,无法完成struct wordcounter
我正在编写一个程序,计算一个单词在文本文件中出现的次数。这是通过使用包含单词及其计数的结构来完成的。我得到一个编译,我得到一个错误,它是: “对不完整的类型struct wordcounter应用sizeof无效。” 如果您对如何解决此问题以及我的代码有任何意见,我们将不胜感激。我是c新手,所以我也愿意接受与这个问题无关的建议。谢谢。我的代码是:sizeof的应用程序无效,无法完成struct wordcounter,c,pointers,struct,malloc,sizeof,C,Pointers,Struct,Malloc,Sizeof,我正在编写一个程序,计算一个单词在文本文件中出现的次数。这是通过使用包含单词及其计数的结构来完成的。我得到一个编译,我得到一个错误,它是: “对不完整的类型struct wordcounter应用sizeof无效。” 如果您对如何解决此问题以及我的代码有任何意见,我们将不胜感激。我是c新手,所以我也愿意接受与这个问题无关的建议。谢谢。我的代码是: #include <stdio.h> #include <string.h> #include <ctype.h>
#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;
}
}
#包括
#包括
#包括
#包括
#定义MAXWORDS 5000
#定义MAXLINE 1000
#定义MAXWORDLEN 100
整数计数=0;
struct wordcount*wordPtr[MAXWORDS];
typedef struct wordcount*wordcountptr;
typedef结构字计数{
字符字[50];
整数计数;
}字数;
main()
{
int-wordfound=0;
内伦;
字符行[MAXLINE];
整数打印计数;
而((len=getline(line,MAXLINE,stdin))>0)
{
int i=0;
int j=0;
对于(;iwordcount
!=wordcounter
。检查您的decl名称与您在代码中使用的名称。顺便说一句,有不止一个。我是否错误地实现了getline?我收到了有关我的参数的警告。现在我还收到了一个运行时错误:分段错误(内核转储)。谢谢,这很有效。所以问题与没有定义结构的实例有关?我现在得到一个运行时错误:分段错误(内核转储)。我理解这与试图访问尚未分配的内存有关。我是否正确使用getline?我收到了有关它的警告,并怀疑是否是它导致了此问题。ssize\t getline(char**lineptr,size\t*n,FILE*stream)这是getline
prototype,第一个参数是char**
,而不是char*
,您可以这样使用:getline(&line,MAXLINE,stdin)
好的。我想我很困惑,因为我认为当你在c中引用数组时,它是指向数组第一个元素的指针。为什么我需要指定行的地址?我想我很困惑char**和char*。我真的很感谢你的帮助。如果第一个agment是NULL,你可以在linux上man getline
,则getline
将分配内存本身,因此getline
必须知道line
的地址才能指向它分配的内存。
typedef struct wordcount {
char word[50];
int count;
} wordcount_t;//modify like this
wordPtr[i] = (wordcount_t*)malloc(sizeof(wordcount_t));//modify like this