一个单词统计题,VC给的反应很奇怪!求解释。
#include <stdio.h>#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "scanner.h"
#include "scanner.cpp"
#define N 20
#define M 100
typedef char *string;
static bool IsLegalWord(string m);
static string ReadLine(FILE *infile);
main()
{
FILE *infile;
char name[N];
string dang,token;
int now=0,i;
int chang,n=1;
int *shu,*tmpshu;
string *ci,*tmpci;
printf("程序将读取一个文件,统计单词出现频率。\n");
printf("请输入文件名:");
scanf("%s",name);
getchar();
infile=fopen(name,"r");
shu=(int*)malloc(M*n+1);
ci=(string*)malloc(M*n+1);
chang=M*n;
/* for(i=0;i<M*n+1;i++){
shu[i]=0;
}
*/
//数组初始化不进行,程序可以运行,删掉注释符,程序出错。
while (true){
dang=ReadLine(infile);
if (dang==NULL) break;
InitScanner(dang);
while (strcmp(token=GetNextToken(),"\0")){
if (IsLegalWord(token)) {
if (now==0) {
ci[now]=token;
shu[now]++;
now++;
}else{
for(i=0;i<now;i++){
if (!strcmp(token,ci[i])) {
shu[i]++;break;
}
}
if (i==now) {
ci[now]=token;
shu[now]++;
now++;
}
}
}
if (now>chang){
n++;
tmpshu=shu;
tmpci=ci;
shu=(int*)malloc(M*n+1);
ci=(string*)malloc(M*n+1);
for(i=0;i<chang+1;i++){
shu[i]=tmpshu[i];
ci[i]=tmpci[i];
}
free(tmpshu);
free(tmpci);
chang=M*n;
}
}
}
for(i=0;i<now;i++){
printf("%s\t%d\n",ci[i],shu[i]);
}
}
static string ReadLine(FILE *infile)
{
char s[10000],*b;
int i=0;
b=fgets(s,10000,infile);//经检验,数组动态初始化后,本句无法运行,这两者有什么关系吗?
if (b==NULL) return (NULL);//程序在VC++6.0环境下调试的
while (s[i++]!='\0') ;
b=(char*)malloc(sizeof(char)*i);
strcpy(b,s);
return (b);
}
static bool IsLegalWord(string m)
{
int n=0,i;
while (m[n]!='\0') n++;
for(i=0;i<n;i++){
if(!isalpha(m[i])) return (false);
}
return (true);
}