2017-02-14 90 views
0

從一個字符串數組中創建一個哈希表,並在我的插入中,我有一個while語句可以處理碰撞和環繞。我玩過它,似乎只在使用條件語句時纔會出現分段錯誤11。下面是我的while循環:由於while循環中的條件而得到分段錯誤

while (numElm != length) 
{ 
    numProbes = 0; 
    int index = hash(newGuest); 
    //handles collision and wraparound 
    while (hashArray[index] != " " && hashArray[index] != "-1") 
    { 
     ++index; 
     index %= length; 
     numProbes = numProbes + 1; 
    } 

    //sets the array at the index eqaul to data 
    hashArray[index] = newGuest; 
    cout << newGuest << " has been inserted at index: " << index << " using " << numProbes << " probes"; 
    break; 

} 

當第二個while循環以兩個條件語句開始時,會出現問題。誰能告訴我爲什麼會發生這種情況?

編輯程序

#include <cassert> 
#include <iostream> 
#include <cstdlib> 
#include <stdlib.h> 
#include <string> 
#include "HashTable.h" 

using namespace std; 

//typedef double value_type; 


HashTable::HashTable(int tableLength) 
{ 
    tableLength = 114; 
    string *hashArray = new string[tableLength]; 
    length = tableLength; 
    numElm = 0; 

    for(int i = 0; i < length; i++) 
    { 
     hashArray[i] = " "; 
    } 
} 


// Returns an array location for a given item key. 
int HashTable::hash(string itemKey) 
{ 
    int value = 0; 
    for (int i = 0; i < itemKey.size(); i++) 
    { 
     value += itemKey[i]; 
    } 
    return (value * itemKey.length()) % length; 
} 

// Adds an item to the Hash Table. 
void HashTable::insertGuest(string newGuest) 
{ 
// int index = hash(newGuest); 
    //hashArray[ index ].insertGuest(newGuest); 
// cout << newGuest << " has been inserted at index: " << index; 

// string s = " "; 
    while (numElm != length) 
    { 
     numProbes = 0; 
     int index = hash(newGuest); 
     //handles collision and wraparound 
     while (hashArray[index] != " " && hashArray[index] != "-1") 
     { 
      ++index; 
      index %= length; 
      numProbes = numProbes + 1; 
     } 

     //sets the array at the index eqaul to data 
     hashArray[index] = newGuest; 
     cout << newGuest << " has been inserted at index: " << index << " using " << numProbes << " probes"; 
     break; 

    } 
} 

// De-allocates all memory used for the Hash Table. 
HashTable::~HashTable() 
{ 
    delete [] hashArray; 
} 
//#endif 
+1

什麼是'hashArray'聲明?事實上。請給出一個完整的[mcve]。 – BoBTFish

+0

你的'index'明顯超出'has​​hArray'。試過調試? – arrowd

+2

你確定'hash(newGuest)'總是返回一個不在數組邊界之外的有效索引嗎? – sigy

回答

2

其餘你不初始化成員變量hashArray,只有本地變量在構造函數hashArray。類中的hashArray保持未初始化狀態,並在使用時導致崩潰。要解決,有

hashArray = new string[tableLength]; 

這解決了這個問題更換

string *hashArray = new string[tableLength]; 

。否則,代碼中存在許多文體和代碼方面的問題,但我希望您會繼續學習如何自行解決這些問題。祝你好運!

+0

謝謝!不能相信這是簡單的! –

+0

嘗試打開警告。我知道MSVC(你可能正在使用)對這個確切的問題有一個警告。 – dascandy