所以我一直在尝试创建一个处理1000个链表的类,并最初声明指向它们的指针。
这是直接处理我的问题的代码:
struct node
{
char name[40];
char numb[12];
node * next;
};
class hashTable
{
public:
//Creates a table of 1000 pointers to linked-list nodes
node * table[1000];
//Functions
void addNode(char name[40], char numb[12])
{
node * temp; //Initializes temp node as pointer
temp = new node; //Points temp node to a new node
int hash = h(g(name)); //The hash of the key (name) used to check nodes
temp = table[hash]; //sets the temporary node to the first node of the list
while (temp->next != 0)
{
//...
在while循环中,我收到错误“访问冲突读取位置0xcccccd00” 我不确定为什么它不能访问表成员,除非是因为这些值还没有被初始化或什么?
答案 0 :(得分:2)
你可能不会做两件事。首先确保您的哈希表已正确初始化以包含所有NULL指针。其次,确保从哈希表中检索的任何指针有效 previous 以取消引用它:
第一期:
hashTable::hashTable() : table()
{
}
此外,您要确保此内容正确清理
hashTable::~hashTable()
{
for (size_t i=0;i<sizeof(table)/sizeof(table[0]); ++i)
{
node *temp = table[i];
while (temp)
{
node *victim = temp;
temp = temp->next;
delete victim;
}
}
}
关于第二个问题:
void addNode(const char *name, const char *numb)
{
int hash = h(g(name)); //The hash of the key (name) used to check nodes
node *temp = table[hash]; //sets the temporary node to the first node of the list
if (temp)
{
// preexisting entry. walk that list looking for matching key.
node **pp = &temp->next;
while (temp)
{
if (0 == strcmp(temp->name, name))
break;
pp = &temp->next;
temp = temp->next;
}
// link to last node if not found in list
if (!temp)
*pp = new node(name, numb);
}
else
{ // no prior entry. create a new one and store it at table[hash].
table[hash] = new node(name, numb);
}
}
注意:上面的代码假设节点类实现为
struct node
{
char name[40];
char numb[12];
node * next;
node(const char* name_, const char *numb_)
: next()
{
strncpy(name, name_, sizeof(name)/sizeof(name[0])-1);
name[ sizeof(name)/sizeof(name[0])-1 ] = 0;
strncpy(numb, numb_, sizeof(numb)/sizeof(numb[0])-1);
numb[ sizeof(numb)/sizeof(numb[0])-1 ] = 0;
}
};
就个人而言,我会使用std::string
答案 1 :(得分:0)
如果hash的值大于(或等于)1000,则temp将指向无效区域。
你正在泄漏由new node
分配的内存,因为你正在覆盖临时变量。