高分求解程序出问题原因
程序所解决的问题:给出一个字符串判断其是否为回文,回文是正读和倒读都一样的字符串。如:acdedca就是回文,而thisiscat就不是回文。程度如下:
#include <string.h>
#include <stdio.h>
int convert(char *s);
main()
{ char s[20];int k;
printf( "Input a string:\n ");
scanf( "%s ",s);
k=convert(s);
if(k==0)
printf( "%s is not a huiwen.\n ",s);
else
printf( "%s is a huiwen\n ");
}
int convert(char *s)
{ char r[20];int j,i=0,n;
if(s==NULL) return 0;
while(s!= '\0 ')
{ s++;i++; }
for(j=0;j <=i;j++)
{ r[j]=s[i]; }
r[j+1]= '\0 ';
n=strcmp(s,r);
if(!n)return 1;
else return 0;
}
出现的问题:能通过编译,但当输入完字符后,运行出现提示说
TC
NTVDM CPU遇到无效的指令。
CS:63bf IP3e87 op:63 f8 01 03 00 选择“关闭”终止应用程序。
不知道是什么原因,请高手指点一下。
[解决办法]
int check(char *s) /*回文 检验函数*/
{
char tmp[20]={0}; /*tmp 逆序存放字符串 s, 然后strcmp 它们即可*/
int i=strlen(s)-1, j=0;
while(i> =0)tmp[j++]=s[i--];
if(strcmp(s, tmp) == 0)return 1;
else return 0;
}
int main()
{
char s[20];int k;
printf( "Input a string:\n ");
scanf( "%s ",s);
k=check(s);
if(k==0)
printf( "%s is not a huiwen.\n ",s);
else
printf( "%s is a huiwen\n ");
system( "pause ");
return 0;
}
[解决办法]
#include <string.h>
#include <stdio.h>
int convert(char *s);
main()
{
char s[20];int k;
printf( "Input a string:\n ");
scanf( "%s ",s);
k=convert(s);
if(k==0)
printf( "%s is not a huiwen.\n ",s);
else
printf( "%s is a huiwen\n ",s); // 注意后面掉了
}
int convert(char *s)
{
char r[20];
int j,i=0,n;
if(*s==NULL) return 0;
while(*s!= '\0 ') //while(s!= '\0 ') 死循环了
{
s++;
i++;
}
for(j=0;j <i;j++)
{
r[j]=s[j];
}
r[j]= '\0 ';
n=strcmp(s,r);
if(!n)
return 1;
else
return 0;
}
LZ运行下,测试如下:
acdedca <enter>
acdedca is a huiwen
[解决办法]
你的程序问题:
while(s!= '\0 ')
{ s++;i++; }
这里 s 指针被移动到了 s串的末尾,
后面
for(j=0;j <=i;j++)
{ r[j]=s[i]; }
这里 访问 s[i] 越界了 .........