【问题标题】:Hash table implementation bad access error哈希表实现访问错误
【发布时间】:2014-12-20 19:35:13
【问题描述】:

我试图为我的项目创建一个哈希表,但我不断收到错误的访问错误。正如编译器告诉我的那样,语法没有错误。我想我在内存分配上犯了一个错误,但我看不到它。任何帮助表示赞赏。

我在这个循环中遇到了错误的访问错误:

hash_itself_p hash_table = (hash_itself_p)malloc(sizeof(hash_itself_t));
for (i = 0; i < 50; i++)
{
    hash_table->data_id[i]->id = -1; // EXC_BAD_ACCESS here
}

这里是所有代码:

#include <stdio.h>
#include <stdlib.h>
#define size 50

typedef struct hash_value
{
    int id;
    int data;
    int key;
} hash_values_t[1], *hash_values;

typedef struct hash_itself
{
    hash_values data_id[size];
} hash_itself_t[1], *hash_itself_p;

int hash_key(int n)
{   
    return ( n*n + 2*n ) % size;
} 

int hash_id(int n)
{
    return n % size;
}

void insert(hash_itself_p hash_table, int person)
{
    int id;
    int key;

    key = hash_key(person);
    id = hash_id(key);

    if (hash_table->data_id[id]->id == -1)
    {
        hash_table->data_id[id]->id = id;
        hash_table->data_id[id]->data = person;
    } 
    else
    {
        int block = id;
        while (hash_table->data_id[block%50]->id != -1)
        {
            block++;
            if (block%50 == id) return;
        }        
        hash_table->data_id[block]->id = id;
        hash_table->data_id[block]->data = person;
    }    
}

void display(hash_itself_p hash_table)
{
    int i;
    for (i = 0; i < size; i++)
    {
        printf("id = %d, data = %d, key = %d \n", hash_table->data_id[i]->id, hash_table->data_id[i]->data, hash_table->data_id[i]->key);
    }
}

int main()
{
    int i;  
    hash_itself_p hash_table = (hash_itself_p)malloc(sizeof(hash_itself_t));
    for (i = 0; i < 50; i++)
    {
        hash_table->data_id[i]->id = -1;
    }
    insert(hash_table, 30);
    display(hash_table);   
}

【问题讨论】:

标签: c hashtable


【解决方案1】:

您已将hash_itself 中的data_id 数组声明为指向hash_value 结构的指针数组。由于这些指针没有被初始化,它访问了无效的内存。

我认为您想直接创建一个结构数组,在这种情况下您需要:

typedef struct hash_itself
{
    hash_values_t data_id[size];
}

【讨论】:

  • 非常感谢。我应该更加小心。
猜你喜欢
  • 2012-04-15
  • 2016-01-20
  • 2016-03-25
  • 2011-10-14
  • 2011-09-15
  • 2021-04-11
  • 2012-06-03
  • 1970-01-01
相关资源
最近更新 更多