C 模式搜索朴素方法

C 模式搜索朴素方法,c,algorithm,pattern-matching,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<

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

#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;
}
#包括
#包括
#包括
int optcount=0;
int searchpattern(char*ms,char*ss,intm,intn)
{
int i,j;

对于(i=0;i已),第一个
fgets
访问未初始化的指针并读取到尚未分配的内存中。 用相应大小的数组替换原始指针:

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

因为您正在使用指针将输入读入内存,所以现在是学习内存分配和取消分配的好时机

应为
文本、子文本
指针分配内存,其大小应等于您要读取的内容的大小

char* text = (char*) malloc(256 * sizeof(char));
char subtext = (char*) malloc(256 * sizeof(char));
不要忘记在程序结束时使用
free
释放分配的内存

free(text);
free(subtext);

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

那么这是一个关于代码前的时间效率问题还是关于代码后的segfault问题?您应该尝试使用
gdb
关于a的内容是什么lgorithm标签吸引了这么多人“修改我的作业”问题?我们必须从某个地方开始。算法是我们想要确保彻底理解所有主题的重要领域之一。Stackoverflow提供了一个很好的学习平台。我意识到还有一个错误。通过使用fgets,当读取换行符时,它会停止读取。所以在我的实际参数中,它应该是m-1,n-1。