2015-01-31 69 views
1

我想做的AC/c + +程序,其中程序接受一個TXT文件與幾個字,每行一個,並找到編輯距離(也稱爲levenshtein距離)與一個特定的詞。運行時錯誤,當我運行程序,但不是當我使用調試器

我有一個奇怪的問題。

當我在代碼塊中運行它時,我的代碼在閱讀了幾個單詞後遇到運行時錯誤。當我使用代碼塊調試器時它調試得很好。

我一直在環顧四周,發現未初始化的變量可能是一個問題。但是,無論何時我評論我所稱的函數minDistancecount[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; 
} 
+0

#1。使用std :: string ans std :: vector。 #2.實現世界現在是一個更美麗的地方。 #3 ???? #4利潤。 – 2015-01-31 19:21:46

+0

在大多數調試器中,它們用零初始化整型變量,因此請嘗試初始化您擁有的整型數組。 – 3bdalla 2015-01-31 19:24:08

+0

應該沒有任何東西叫'我試圖做一個C/C++程序'。這兩個___是不同的語言,意思是不同的。 – 2015-01-31 19:28:46

回答

2

發現在你的代碼行:

int **d = new int*[l2 + 1]; 
for(i=0;i<l1+1;++i) 

您的(l2 + 1)一些int*分配內存並正在從0 to (l1 + 1)循環i。所以如果l2 < l1,你正在訪問你沒有分配的內存。

也不要混用C++和C,要麼使用C,要麼堅持使用C++。如評論中所述,如果您可以使用C++,請使用std::vectorstd::string - 它會減少您的頭痛。還可以使用C++的IO類來執行文件IO並始終關閉您打開的任何文件。 (即在C中,使用fclose(file_ptr))。

+0

是的,我看到我錯了。對載體的一點研究和我能解決問題。非常感謝。 :) – user3508140 2015-01-31 20:48:54

0

您使用l2作爲第二個索引。它應該是你的第一個索引,並且是你的第二個索引。

// the edit distance between an empty string and the prefixes of 
// word2 
for (i = 0; i < l1 + 1; i++) { 
    d[0][i] = i; 
} 
+0

阿卡什打我吧! – sandman 2015-01-31 20:19:08

+0

哈哈。不管怎樣,謝謝你。 :) – user3508140 2015-01-31 20:50:28

相關問題