小程序、编译通过,但为什么一运行就出错啊解决办法
小程序、编译通过,但为什么一运行就出错啊
#include <stdio.h>
#include <stdlib.h>
void Digif(char *s);
int main(void)
{
char *s;
puts("enter a string...");
gets(s);
Digif(s);
system("PAUSE");
return 0;
}
void Digif(char *s)
{
int n=0;
while(s!=NULL)
{
if( *s++>='0'&&*s++<='9')
{
n++;
}
printf("%d digi founded\n",n);
}
}
------解决方案--------------------
改正(1)char *s;处应改为:
char *s;
s=(char *)malloc(1000);
原因:指针没分配空间
改正(2)if( *s++>='0'&&*s++<='9')处应改为:
if( *s>='0'&&*s<='9')
{
s++;
n++;
}
原因:*s++指的是指针指向的内容加1,而不是指针向后移1位;
&&前后都有*s++,会使*s加2,而不是加1.
#include <stdio.h>
#include <stdlib.h>
void Digif(char *s);
int main(void)
{
char *s;
puts("enter a string...");
gets(s);
Digif(s);
system("PAUSE");
return 0;
}
void Digif(char *s)
{
int n=0;
while(s!=NULL)
{
if( *s++>='0'&&*s++<='9')
{
n++;
}
printf("%d digi founded\n",n);
}
}
------解决方案--------------------
改正(1)char *s;处应改为:
char *s;
s=(char *)malloc(1000);
原因:指针没分配空间
改正(2)if( *s++>='0'&&*s++<='9')处应改为:
if( *s>='0'&&*s<='9')
{
s++;
n++;
}
原因:*s++指的是指针指向的内容加1,而不是指针向后移1位;
&&前后都有*s++,会使*s加2,而不是加1.