#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");
}
计算nextval,字符串数组在经过get_nextval函数后消失了
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- 爱晚乏客游 2021-04-07 17:33关注
你的main函数里面的 int nextval[] = {0}; 这么写开辟的netval空间只有1,分配的静态空间,但是你下面又想要它是一个动态增长的数组,所以报错
改成 int nextval[100] = {0};
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用
悬赏问题
- ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
- ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
- ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
- ¥15 帮我写一个c++工程
- ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
- ¥15 关于smbclient 库的使用
- ¥15 微信小程序协议怎么写
- ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
- ¥20 怎么用dlib库的算法识别小麦病虫害
- ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启