模式搜索朴素方法

时间:2018-08-23 18:59:11

标签: c algorithm pattern-matching

编写一个程序来实现强力字符串匹配,分析其时间效率。 以下是我的代码:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int opcount=0;
int searchpattern(char *ms,char *ss,int m,int n)
{
  int i,j;
  for(i=0;i<=n-m;i++)
  {
    j=0;
    opcount++;
    while(j<m&&(ms[i+j]==ss[j]))
    {
      j++;

    }
    if(j==m){
      //printf("Pattern found in main string");
      return i;
    }
  }
  //printf("Pattern not found");
  return -1;
}
int main()
{
  int i,j,p,n,m;
  char *text;
  char *subtext;
  printf("Enter text below :\n");
  fgets(text,256,stdin);
  printf("Enter subtext below:\n");
  fgets(subtext,256,stdin);
  n=strlen(text);
  m=strlen(subtext);
  p=searchpattern(text,subtext,m,n);
  if(p==-1){
    printf("Pattern not found\n");
  }
  else{
    printf("Pattern found at index %d",p);
  }
  printf("No. of operations is %d",opcount);
  return 0;
}

运行该程序时出现段错误。如果有人指出我的错误,我将不胜感激。

2 个答案:

答案 0 :(得分:0)

第一个fgets已访问未初始化的指针,并读入未分配的内存。 将原始指针替换为相应大小的数组:

char text[256];
char subtext[256];

答案 1 :(得分:0)

由于您正在使用指针将输入读取到内存中,因此这是学习内存分配和取消分配的好时机。

text, subtext指针应分配有内存,其大小应等于您要读取的内容。

char* text = (char*) malloc(256 * sizeof(char));
char subtext = (char*) malloc(256 * sizeof(char));

请不要忘记使用free释放程序末尾分配的内存。

free(text);
free(subtext);

mallocfree函数是stdlib.h中的库函数,因此您必须将此标头添加到文件的开头。