cxSnowJohn 2021-04-07 17:15 采纳率: 50%
浏览 38
已采纳

计算nextval,字符串数组在经过get_nextval函数后消失了

#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");
}
 

  • 写回答

2条回答 默认 最新

  • 爱晚乏客游 2021-04-07 17:33
    关注

    你的main函数里面的    int nextval[] = {0}; 这么写开辟的netval空间只有1,分配的静态空间,但是你下面又想要它是一个动态增长的数组,所以报错

    改成  int nextval[100] = {0};

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?