C语言 程序运行到一半告诉我出现一个问题导致程序停止工作
char *rwtab[27]={"main","if","then","while","do"," static","int",
" double","struct","break","else","long","switch","case",
"typedef","char","return","const","float","short","continue",
"for","void","sizeof","default","do"};
这是子程序
void IsLetter(char alpha)
{
char ch2=alpha;
x=0;
while((ch2>='0' && ch2<='9')||(ch2>='a' && ch2<='z')||(ch2>='A' && ch2<='Z'))
{
token[x]=ch2;
x++;
j++;
ch2=done[j];
}
syn=25;
for(n=0;n<27;n++)
if(strcmp(token,rwtab[n])==0)
{
//我只要在这里面写任意一句话就会告诉我程序出现问题,如果我什么都不写,程序是可以运行的,于是我就蒙了
}
fprintf(fp,"<%d,%s>\n",syn,token);
memset(token,0,sizeof(token));
}
想要完整程序的在这里http://yun.baidu.com/share/link?shareid=4293521057&uk=3271769907
很急!!很急!!求助!!!!!!
谢谢各位大神!!!!!!!!!!!!!!!!!!!!!!
那个……12点以前没有回答的话我就收回了………… 展开
有点儿意思。原因却出乎意料的简单。
char *rwtab[27]={"main","if","then","while","do"," static","int",
" double","struct","break","else","long","switch","case",
"typedef","char","return","const","float","short","continue",
"for","void","sizeof","default","do"};
少了一项,只有26项,rwtab[26]是空指针,访问到它时,就出错了。错误提示如下:
我没有修改这一句的时候,在你指出出错的地方加了下面一句:
for(n=0;n<27;n++)
if(strcmp(token,rwtab[n])==0)//比较是否关键字
{
printf("Cathch a key-word\n"); //
}
出错了,提示信息如下:
这意味着,访问了一个空指针。
修改如下:
char *rwtab[27]={"main","if","then","while","do","static","int",\
"double","struct","break","else","long","switch","case",\
"typedef","char","return","const","float","short","continue",\
"for","void","sizeof","default","do","long"};//数组少一项,没有27项,另外几个关键词前面有空格,也应该删除。 加了续行符号。
修改之后,运行成功:
我用你的程序做a.txt,生成文件b.txt,c.txt,今天不知什么情况,不能上传。
为什么这样?很玄妙:
rwtab数组少一项,rwtab[26]会引用一个空指针,产生错误。这儿没有语句时,循环没有实质性语句,编译程序优化, 不会编译这个循环的语句,程序中根本没有这几句的内容,因而不会出错。有了语句,就不能省略了,就出错了。
就是这样简单。
另外,你的程序必须当做C++程序编译,否则通不过。C不允许在有实质语句之后定义变量,变量说明要全部放到相应段的最前面,也不支持//注释。我是用DEVC++编译成功的,用WINTC编译失败。