繁体   English   中英

获取分段错误11如果在C中正确使用指针,则不确定

[英]Getting a Segmentation Fault 11 Not Sure if Using Pointers Correctly in 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);




}

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

您的代码布局很棒,而且易于阅读!

以下是错误的

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

基于

struct hashTable *newTable;

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM