首页 > 解决方案 > 在 C 中打印最长公共子字符串的代码

问题描述

我编写了代码来打印 C 语言编程中最长的公共子字符串。当我运行代码时,它显示“已转储分段核心”。请帮助我,我想知道这个问题,因为它一开始可以工作,然后突然出现这个错误。

#include<string.h>
#include <stdio.h>
#define new_max(x,y) (((x) >= (y)) ? (x) : (y))
#define new_min(x,y) (((x) <= (y)) ? (x) : (y))

void LCSubStr(char *X, char *Y, int m, int n)
{
    int LCSuff[m+1][n+1];
    int result = 0;
    int end;

    for (int i=0; i<=m; i++)
    {
        for (int j=0; j<=n; j++)
        {

            if (i == 0 || j == 0)
                LCSuff[i][j] = 0;

            else if (X[i-1] == Y[j-1])
            {
                LCSuff[i][j] = LCSuff[i-1][j-1] + 1;
                result = new_max(result, LCSuff[i][j]);
                end = i - 1;
            }
            else{
         LCSuff[i][j] = 0;
        }
        }
    }

    if(result = 0){
        printf("No common substring");
    }else{
        char subbuff[5];
        memcpy(subbuff, &X[end - result + 1], result);
        subbuff[result] = '\0';
        printf("%s",subbuff);
    }
}

int main()
{
    char X[] = "Sandile";
    char Y[] = "andile";

    int m = strlen(X);
    int n = strlen(Y);

    LCSubStr(X, Y, m, n);
    return 0;
}

标签: c

解决方案


我相信,在这个声明中

if(result = 0){

=是错字,你的意思是==ie if (result == 0) ...

您的程序正在访问超出其大小的数组,这是一种未定义的行为:

        char subbuff[5];
        memcpy(subbuff, &X[end - result + 1], result);

对于给定的输入 (和), issubbuff的大小和最长公共子串的大小是。,在复制字节时,最终会访问超出其大小的数组。您需要一个最小大小(字符+空终止字符)的目标缓冲区来保存公共子字符串(对于给定的输入)。5X = "Sandile"Y = "andile"6memcpysubbuff761

正如@Halt State 建议的那样,您可以从字符串中的某个位置开始打印输入字符串的特定字符数:

    if(result = 0){
        printf("No common substring");
    }else{
        printf("%.*s",result, &X[end-result+1]);
    }

或者,您可以动态分配内存并复制该内存中最长的公共字符串。LCSubStr()在这种情况下,如果需要,您可以从函数中返回它,而不是在函数中打印最长的公共字符串,LCSubStr()这使调用函数能够根据返回的字符串处理某些内容。它的实现:

....
#include <stdlib.h>    // for malloc
....

char * LCSubStr (char *X, char *Y, int m, int n) {
    ....
    ....
    char * subbuff = NULL;
    if (result > 0) {
        subbuff = malloc (result + 1);
        if (subbuff == NULL) {
            fprintf (stderr, "Failed to allocate memory\n");
            exit (EXIT_FAILURE);
        }
        memcpy (subbuff, &X[end - result + 1], result);
        subbuff[result] = '\0';
    }
    return subbuff;
}

// In the calling function
int main (void) {
    ....
    ....
    char * lcs = LCSubStr (X, Y, m, n);
    if (lcs != NULL) {
        printf ("%s\n", lcs);
        // Once the calling function done with returned buffer, free it
        free (lcs);
    } else {
        printf ("No common substring\n");
    }

    return 0;
}

推荐阅读