c++哈希表和链表的访问冲突
C++ Access Violation With Hash Tables and Linked Lists
所以我一直在尝试创建一个处理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"我不知道为什么它不能访问表成员,除非可能是因为这些值还没有初始化或什么?
您可能没有做两件事。首先,确保正确初始化哈希表以包含全空指针。其次,确保从哈希表中检索到的任何指针都是有效的优先于对其解引用:
第一期:
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
如果hash值大于(或等于)1000,temp将指向无效区域
并且您正在泄漏由new node
分配的内存,因为您正在覆盖temp变量。
相关文章:
- 链表中写入访问冲突的未知原因
- 为什么我在空指针错误(链表)中获取成员访问权限
- 在C++中删除双向链表的头节点后出现访问冲突异常
- 循环访问自定义双链表
- 如何通过不同的指针使用类的对象访问结构?(链表)(C++)
- 尝试从单向链表C++中删除单个节点时出现读取访问冲突
- 链表的访问冲突异常
- C++链表读取访问冲突
- 我如何能够访问双向链表中的嵌套结构
- c++ 访问单个链表中的特定值
- 存储类对象的C++模板链表-未处理的异常访问冲突读取位置
- 在C++中读取链表上的访问冲突
- 链表访问冲突写入位置
- 链表访问冲突
- 写入位置c++链表时发生访问冲突
- 打印链表-访问冲突c++
- 如何使用boost::iterator_facade来访问遗留链表
- c++哈希表和链表的访问冲突
- 如何访问C++链表中的对象数据
- 复制构造函数后链表中的访问冲突