[英]Code to print the Longest Common Substring in C
我編寫了代碼來打印 C 語言編程中最長的常見 substring。 當我運行代碼時,它顯示“已轉儲分段核心”。 請幫助我,我想知道這個問題,因為它一開始可以工作,然后突然出現這個錯誤。
#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;
}
您可以直接使用 printf 指定長度,而不是復制到固定長度的字符串。
char subbuff[5];
memcpy(subbuff, &X[end - result + 1], result);
subbuff[result] = '\0';
printf("%s",subbuff);
相反,請嘗試:
printf("%.*s",result, &X[end-result+1])
('.*s' 語法在參數列表中使用了一個限制——在這種情況下是匹配的result
或長度)
另外,請注意=
。
if(result = 0){
printf("No common substring");
傳統的做法是在 C 中進行反向比較以避免這種錯字。
if (0 == result) {
printf("No common substring");
我相信,在這個聲明中
if(result = 0){
=
是錯字,你的意思是==
即if (result == 0)...
。
您的程序正在訪問超出其大小的數組,這是一種未定義的行為:
char subbuff[5];
memcpy(subbuff, &X[end - result + 1], result);
對於給定的輸入( X = "Sandile"
和Y = "andile"
), subbuff
的大小為5
,最長公共 substring 的大小為6
。 memcpy
在復制字節時,最終會訪問超出其大小的數組subbuff
。 您需要一個最小大小為7
的目標緩沖區( 6
字符 + 1
null 終止字符)來保存常見的 substring(對於給定的輸入)。
正如@Halt State 建議的那樣,您可以打印輸入字符串的特定字符數,從字符串中的 position 開始:
if(result = 0){
printf("No common substring");
}else{
printf("%.*s",result, &X[end-result+1]);
}
或者,您可以動態分配 memory 並復制該 memory 中最長的公共字符串。 在這種情況下,您可以從LCSubStr()
function 返回它,而不是在LCSubStr()
function 中打印最長的公共字符串,這使得調用 ZC1C425268E68385D14AB5074C17A 能夠基於返回的字符串、F14AB5074C17A 進行處理。 它的實現:
....
#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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.