#include<Stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#define MAX 200
typedef struct
{
char ch[MAX];
int length;
}string;
void initstring(string &S) //串的输入
{
char e;
int i = 1;
printf("请输入字符串:");
scanf("%c", &e);
while(e !='\n')
{
S.ch[i] = e;
i++;
scanf("%c", &e);
}
S.length = i-1;
}
void printfstring(string &S) //打印串
{
int i;
printf("线性表内字符串为:");
for(i = 1; i <= S.length; i++)
{
printf("%c", S.ch[i]);
}
printf("\n");
}
bool substring(string &Sub,string S, int pos, int len) //输出串S的一个子串,子串为第pos个位置开始后一共len个字符
{
if(pos<1 || len<0 || pos>S.length || pos+len-1>S.length)
return false;
for(int i = 1; i <= len; i++)
Sub.ch[i] = S.ch[pos+i-1];
Sub.length = len;
printfstring(Sub);
return true;
}
int index(string S,string T) //模式匹配BF算法
{
int i = 1,j = 1;
while(i<=S.length && j<=T.length)
{
if(S.ch[i] == T.ch[j])
{
i++; j++;
}
else
{
i = i - j + 2;
j = 1;
}
}
if(j>=T.length) return i-T.length;
else return 0;
}
void nextarray(string S, int *next)
{
next = (int*)malloc(MAX * sizeof(int));
next[1] = 0;
int j = 0;
int i = 1;
while(i < S.length)
{
if(j == 0 || next[i] == next[j])
next[i++] = ++j;
else
j = next[j];
}
next[0] = S.length;
}
void printfnext(int *next)
{
int i;
printf("next数组中的数据为:");
for(i = 1; i <= next[0]; i++)
printf("%d", next[i]);
}
int main(void)
{
string S;
initstring(S);
printfstring(S);
string Sub;
int pos,len;
printf("请输入你要获取串S中子串的起始位置和长度:");
scanf("%d %d", &pos,&len);
substring(Sub, S, pos, len);
int e;
e = index(S, Sub);
printf("子串Sub在主串S的第%d个位置处", e);
int *next;
nextarray(Sub, next);
printfnext(next);
return 0;
}
为什么运行到这里不动了,也不结束,也出不来next数组,这是什么问题呢,来个人给我看一看吧