#include <stdio.h>
#include <stdlib.h>
void Index_KMP(char str1[], char str2[], int nextval[]);
void Get_nextval(char str[], int nextval[]);
int StrLen(char str[]);
void Show(char str[]);
int main()
{
char str1[100];
char str2[100];
int nextval[] = {0};
//scanf("%s %s", str1, str2);
gets(str1);
gets(str2);
//Show(str2);
Get_nextval(str2, nextval);
Index_KMP(str1, str2, nextval);
}
void Get_nextval(char str[], int nextval[])
{
int m;
int i = 1;
nextval[0] = 0;
int j = 0;
m = StrLen(str);
//printf("%d\n", m);
//Show(str);
while(i <= m)
{
if(j == 0 || str[i - 1] == str[j])
{
++i;
++j;
if(str[i- 1] != str[j - 1])
{
nextval[i - 1] = j;
}
else
{
nextval[i - 1] = nextval[j - 1];
}
}
else
{
j = nextval[j];
}
}
Show(str);
}
int StrLen(char str[])
{
int i = 0;
while(str[i] != '\0')
{
++i;
}
return i;
}
void Index_KMP(char str1[], char str2[], int nextval[])
{
int i = 1, j = 1;
int m = StrLen(str1), n = StrLen(str2);
//Show(str2);
//printf("主串长度为:%d\n子串长度为:%d\n", m, n);
while(i <= m && j <= n)
{
if(j == 0 || str1[i - 1] == str2[j - 1])
{
++i;
++j;
}
else
{
j = nextval[j - 1];
}
}
if(j >= n)
{
printf("%d", i - j);
}
else
{
printf("fail");
}
}
void Show(char str[])
{
int i =0;
while(str[i] != '\0')
{
printf("%c", str[i]);
++i;
}
printf("\n");
}
你的main函数里面的 int nextval[] = {0}; 这么写开辟的netval空间只有1,分配的静态空间,但是你下面又想要它是一个动态增长的数组,所以报错
改成 int nextval[100] = {0};
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,欢迎您加入CSDN!
目前问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632