由于while循环中的条件,导致Segmentation错误

Getting a Segmentation fault because of conditions in while loop

本文关键字:导致 Segmentation 错误 条件 while 循环 由于      更新时间:2023-10-16

我用字符串数组制作了一个哈希表,在插入中,我有一个while语句,用于处理冲突和环绕。我已经试过了,似乎只有在使用条件语句时才会出现分段错误11。这是我的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

您没有初始化成员变量hashArray,在构造函数中只有局部的变量hashArray。类中的hashArray保持未初始化状态,使用时会导致崩溃。要修复,请更换

string *hashArray = new string[tableLength];

带有

hashArray = new string[tableLength];

这解决了问题。在其他方面,代码有很多风格和代码方面的问题,但我希望您能继续学习自己解决这些问题。祝你好运