gpt4 book ai didi

c++ - 在对象指针数组上调用函数

转载 作者:行者123 更新时间:2023-11-30 04:27:18 25 4
gpt4 key购买 nike

我在任何地方都找不到类似的东西。我有一个哈希表的对象指针数组(链表):

LinkList * table[TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; i++)
table[i] = NULL;

在我的哈希表类的函数之一中,我需要调用 table 数组中的 LinkList 对象的函数之一。我这样调用它:

void HashMap::add_customer(string first, string last, string phone) {   
int hash = get_hash(phone);
if (table[hash] == NULL) {
table[hash] = new LinkList;
}
table[hash]->add_customer(first, last, phone); // I HATE THIS LINE
}

一切都可以正常编译,但是当我在运行时执行 table[hash]->add_customer() 行时,出现了 Segmentation Fault 错误。当这一行被注释掉时,我没有得到任何错误,但显然,我无法将任何客户添加到我的哈希表中。这不是正确的语法吗?

最佳答案

您必须将指针数组初始化为 NULL,因为它们将被分配到堆栈/堆或任何具有垃圾值的地方....

LinkList * table[TABLE_SIZE];
memset(table, NULL, sizeof(LinkList *) * TABLE_SIZE);

假设您已经正确初始化,那么请检查您的哈希值并断言它们确实是哈希值 < TABLE_SIZE

试试这个:

 int hash = get_hash(phone) % TABLE_SIZE;

关于c++ - 在对象指针数组上调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11006329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com