首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

请教此程序错在哪里?如何改

2012-03-27 
请问此程序错在哪里?怎么改?题目:编写一个函数sort(char*str,char*substr),它的功能是:统计子字符串substr

请问此程序错在哪里?怎么改?
题目:编写一个函数sort(char   *str,char   *substr),它的功能是:统计子字符串substr在字符串str中出现的次数。

#include   "stdio.h "
#include   "string.h "
int   sort(char   *str,char   *substr)
{char   *p;
  int   n=0,x;
  x=strlen(substr);
  while   (str!=NULL)
  {str=strstr(str,substr);
    str=str+x;
    n++;}
    return   n;
}

int   main()
{char   *str,*substr;
  int   n;
  str=(char   *)malloc(30);
  substr=(char   *)mallocx(10);
  gets(str);
  gets(substr);
  n=sort(str,substr);
  printf( "%d ",n);
}




[解决办法]
#include "stdio.h "
#include <malloc.h>
#include "string.h "
#include <stdlib.h>
int sort(char *str,char *substr)
{char *p;
int n=0,x;
x=strlen(substr);
while (*str!=NULL) //此处因应该是内容为0,而不是地址为空
{str=strstr(str,substr); //循环体内没有对是否找到作判断,如果str==null
if(str==NULL)break; //其结果就不可知了
else
{str=str+x;
n++;
}
}
return n;
}

int main()
{char *str,*substr;
int n;
str=(char *)malloc(30);
substr=(char *)malloc(10);
gets(str);
gets(substr);
n=sort(str,substr);
printf( "%d ",n);
}

热点排行