【发布时间】:2014-07-13 11:35:43
【问题描述】:
我一直在尝试创建一个在文件中搜索特定单词的函数...我的程序编译了,但它的执行在某个时候终止了... 功能是:
void search(struct word *w,FILE *f)
{
char *c,*c2;
int i,j,n,k,l;
c=(char*)malloc(120*sizeof(char));
c2=(char*)malloc(20*sizeof(char));
while(f!=NULL)
{
j=0;
i=1;
fscanf (f,"%[^\n]%*c",c);
printf("%s",c);
n=strlen(c);
k=0;
l=j;
while(l<=n && *(c+j)!=' ')
{
*(c2+k)=*(c+j);
printf("1");
printf("%s",*(c2+k));
printf("2");
k=k+1;
l=l+1;
}
if(w->name==c2)
{
insert(i,j+1,name,&w);
}
else
{
if(l<n)
j=l+1;
k=0;
c2=(char*)malloc(20*sizeof(char));
l=j;
}
i=i+1;
j=0;
}
}
主要功能是:
int main()
{
FILE *f;
struct word *s;
s=(struct word*)malloc(sizeof(struct word));
struct word *hashtable[100];
s->name=(char*)malloc(20*sizeof(char));
scanf("%s",s->name);
f=fopen("fileA.txt","rt");
char *name="fileA.txt";
search(s,f);
printresults();
system("pause");
return(0);
}
结构是:
struct position
{
char *filename;
int line;
int place;
struct position *next;
};
struct word
{
char *name;
struct word *right;
struct word *left;
struct position *result;
};
程序在printf("1") 和printf("2") 之间终止。
我的代码有什么问题?
【问题讨论】:
-
两件事:Don't cast the result of
malloc和sizeof(char)被指定为始终为 1。 -
"..它的执行会在某个时候终止.." 对于许多最终用户程序来说,这是完全正常的。
-
好吧,@JoachimPileborg 你是对的......!我认为 %s 也会这样......!谢谢!
-
但是,还是有问题……读完我的文件第一行后,程序又终止了……这次是什么问题?