一个C语言写的词法分析程序,出现access violation错误,请各位大虾帮帮忙
阿尔法糯米 2011-10-18 06:27:32 代码如下:#include <stdio.h>
#include <string.h>
#include <ctype.h>
//#pragma comment(lib,"d3d9.lib")
#include <stdlib.h>
char *a[19]={ "char ", "continue ","while", "do ", "double ", "else ", "float ", "for ", "if ", "int ",
"long ", "return ", "short ", "switch ", "void ", "while ", "float ","printf","scanf"};
char *b[13]={ "&& ", "|| ", "++ ", "-- ", "+ ", "- ", "* ", "/ ", "= ", "> ", " < ", "== ", "!= "};
char *c[10]={ "[ ", "] ", "{ ", "} ", "( ", ") ", ", ", "; ", " ' ",":"};
//是否为关键字
int test1(char *str){
int i=0;
for( i=0;i<17;i++)
{
if(strcmp(str,a[i])==0)
{
printf("(%ssym, )",a[i]);
break;
}
}
if(i<17&&i>=0) return 1;
else return 0;
}
//判断是否为运算符
int test2(char *str){
int i;
for(i=0;i<13;i++)
{
if(strcmp(str,b[i])==0)
{
switch(i)
{
case 0 :printf("(与运算, )");
case 1 :printf("(或运算, )");
case 2 :printf("(自加运算, )");
case 3 :printf("(自减运算, )");
case 4 :printf("(加运算, )");
case 5: printf("(减运算, )");
case 6:printf("(乘运算, )");
case 7:printf("(除运算, )");
case 8:printf("(赋值运算, )");
case 9:printf("(大于运算, )");
case 10:printf("(小于运算, )");
case 11:printf("(等于运算, )");
case 12:printf("(不等于运算, )");
}
break;
}
}
if(i<13&&i>=0) return 1;
else return 0;
}
//判断是否为分界符
int test3(char *str){
int i=0;
for(i=0;i<10;i++)
{
if(strcmp(str,c[i])==0)
{
switch(i)
{
case 0: printf("(左半中括号, )");
case 1: printf("(右半中括号, )");
case 2: printf("(左半花括号, )");
case 3: printf("(右半花括号, )");
case 4: printf("(左半小括号, )");
case 5: printf("(右半小括号, )");
case 6: printf("(逗号, )");
case 7: printf("(分号, )");
case 8: printf("(引号, )");
case 9: printf("(冒号, )");
}
break;
}
}
if(i<10&&i>=0) return 1;
else return 0;
}
//主函数及函数调用关系
void main(){
FILE *fp;
char ch,filename[20];
char temp[20];
int i=0;
printf("请输入要分析的文件名:");
scanf("%s",filename);
if((fp=fopen(filename,"r"))==NULL)
{
printf("打开文件失败\n");
exit(0);
}
getchar();
ch=getc(fp);
while(!feof(fp)){
i=0;
if(ch!='\0'){
if(ch<='9'&&ch>='0')
{
do{
temp[i]=ch;
ch=getc(fp);
if(ch<'0'||ch>'9') { printf("错误的定义");break;}
else
{ i++;
temp[i]=ch;
i++;
ch=getc(fp);
}
}while((i!=0)&&(ch!='\0'));
temp[i]=ch;
printf("(数字,%d)",atoi(temp));
}
else
{
do{
temp[i]=ch;
i++;
ch=getc(fp);
}while(ch!='\0');
temp[i]='\0';
test1(temp);
if(test1(temp)==0) test2(temp);
if(test2(temp)==0) test3(temp);
if(test3(temp)==0) printf("(变量,%s)",temp);
}
}
ch=getc(fp);
}
fclose(fp);
}