我正在尝试制作一个 c/c++ 程序,该程序接受一个包含多个单词的 txt 文件,每行一个,并找到具有特定单词的编辑距离(也称为 levenshtein 距离)。
我有一个奇怪的问题。
当我在代码块中运行它时,我的代码在读取几个单词后遇到运行时错误。当我使用代码块调试器时,它调试得很好。
我环顾四周,发现未初始化的变量可能是个问题。但是每当我评论调用函数 minDistance
count[i]=minDistance(word,lines[i]);
的行时,代码运行良好并打印出来文件中的所有单词。所以我想这不是问题。
任何帮助都会很棒。谢谢。
代码如下。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include<iostream>
using namespace std;
static int minDistance(char* word1, char* word2)
{
const int l1 = strlen(word1);
const int l2 = strlen(word2);
int i=0,j=0;
int **d = new int*[l2 + 1];
for(i=0;i<l1+1;++i)
d[i]=new int[l1+1];
// the edit distance between an empty string and the prefixes of
// word2
for (i = 0; i < l2 + 1; i++) {
d[0][i] = i;
}
// the edit distance between an empty string and the prefixes of
// word1
for (j = 0; j < l1 + 1; j++) {
d[j][0] = j;
}
for (i = 1; i < l1 + 1; i++) {
for (j = 1; j < l2 + 1; j++) {
if (word1[i - 1] == word2[j - 1]) {
d[i][j] = d[i - 1][j - 1];
} else {
d[i][j] = min(min(1 + d[i][j - 1], 1 + d[i - 1][j]),
1 + d[i - 1][j - 1]); // min of insertion,
// deletion, replacement
}
}
}
return d[l1][l2];
}
void lines()
{
int i=0;
char * lines[10];
int count[10];
char word[]="book";
FILE *file_handle = fopen ("wordlist.txt", "r");
for (i =0; i < 5; ++i)
{
lines[i] = (char*)malloc (128); /* allocating a memory slot of 128 chars */
fscanf (file_handle, "%s", lines[i]);
count[i]=minDistance(word,lines[i]);
cout<<lines[i]<<" ";
cout<<count[i]<<endl;
}
for (i =0; i < 5; ++i)
free (lines[i]);
}
int main (int argc, char *argv[])
{
lines();
return 0;
}
最佳答案
注意代码中的行:
int **d = new int*[l2 + 1];
for(i=0;i<l1+1;++i)
您正在为 (l2 + 1)
分配内存数量int*
你正在循环 i
来自 0 to (l1 + 1)
.所以如果l2 < l1
,您正在访问尚未分配的内存。
也不要混合使用 C++ 和 C。要么使用 C,要么坚持使用 C++。如评论中所述,如果您可以使用 C++,请使用 std::vector
和 std::string
- 它会减少你的头痛。还可以使用 C++ 的 IO 类来执行文件 IO 并始终关闭您打开的任何文件。 (即在 C 中,使用 fclose(file_ptr)
)。
关于c++ - 运行程序时出现运行时错误,但使用调试器时却没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28255520/