获得分割故障11不确定是否使用指针正确在C



请记住,我是C的新手,整个指针/内存分配对我来说有点棘手。通过终端输入的命令行参数也是如此。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct node {
    long long key;
    long long val;
    struct node *next;
}; 
struct hashTable {
    struct node *head;
    int buckets;
}; 
int count = 0;
struct hashTable *newTable;
//create a new node
struct node * createNode (long long key, long long val) {
    struct node *newNode;
    newNode = (struct node *) malloc(sizeof(struct node));
    newNode -> key = key;
    newNode -> val = val;
    newNode -> next = NULL;
    return newNode;
}
//insert data into Hash
void insertToHash(long long key, long long val) {
    // hash func
    int hashIndex = key % 1000, inTable = 0;
    struct node *newNode = createNode(key, val);
    //traversal nodes
    struct node *temp, *curr;
    curr = newTable[hashIndex].head;
    //if the table at given index is empty 
    if (newTable[hashIndex].head == NULL) {
        newTable[hashIndex].head = newNode;
        count ++;
        return;
    }
    temp = curr;
    //if key is found break, else traverse till end
    while(curr != NULL) {
        if (curr -> key == key) {
            inTable = 1;
            free(newNode); //since already in the able free its memory
            break;
        }
        else {
            temp = curr;
            curr = curr->next;
        }
    }
    if (inTable == 1) {
        printf("Address is already in the table");
    }
    //key not found so make newNode the head
    else {
        newNode -> next = newTable[hashIndex].head;
        newTable[hashIndex].head = newNode;
        count ++;
    }
}
//initialize hashtable to 1000 entries
struct hashTable * createHashTable (int buckets) {
    int i;
    for(i=0; i<buckets; i++) {
        newTable[i].head = NULL;
    }
    return newTable;
}

int main(int argc, char *argv[]) {
    createHashTable(1000);


}

所以当我搜索什么是分割故障11时,我发现它与无法访问某些内存有关。我假设我的问题与初始化表newTable和不正确使用指针或正确分配内存有关。请记住,这是我第一次真正尝试用C语言创建数据结构,所以看起来很明显的事情对我来说并不明显。

你的代码布局很棒,很容易阅读!

下面是错误的

for(i=0; i<buckets; i++) {
    newTable[i].head = NULL;
}
根据

struct hashTable *newTable;

newTable是指向单个结构体的指针,而不是指向数组的指针。

关于正确的解决方案,请先参照K&R书中的哈希表示例,然后根据您的需要随意修改。

相关内容

  • 没有找到相关文章

最新更新