c - 在 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;
}
解决方案
我相信,在这个声明中
if(result = 0){
=
是错字,你的意思是==
ie if (result == 0) ...
。
您的程序正在访问超出其大小的数组,这是一种未定义的行为:
char subbuff[5];
memcpy(subbuff, &X[end - result + 1], result);
对于给定的输入 (和), issubbuff
的大小和最长公共子串的大小是。,在复制字节时,最终会访问超出其大小的数组。您需要一个最小大小(字符+空终止字符)的目标缓冲区来保存公共子字符串(对于给定的输入)。5
X = "Sandile"
Y = "andile"
6
memcpy
subbuff
7
6
1
正如@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;
}
推荐阅读
- python - 如何使用 TensorFlow 的渴望执行检查我的张量的内容?
- deep-learning - 我可以分配我的训练数据并训练每个部分,而不是一次输入我的全部数据吗?
- swift - 如何从套接字获取数据并制作 protobuf 文件?
- xml - odoo 表单视图中的 XML 整数格式
- android - 资源样式项目名称“android:blablabla”红色突出显示,不工作,没有错误
- fuzzy-search - 在云上的 db2(以前的 dashdb)上使用“db2 文本搜索”
- vaadin - Cypress 和 Vaadin 应用程序将触发一个错误弹出窗口,阻止测试正常工作
- c# - 用于 Edge 本机消息传递的应用服务桌面桥不起作用
- sql - 更新从 sys.columns 和 sys.tables 中选择的表中的值
- javascript - 对 HTML5 视频使用基于令牌的身份验证