【发布时间】:2017-03-04 03:04:17
【问题描述】:
请记住,我是 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 中创建数据结构,所以看起来很明显的事情对我来说并不明显。
【问题讨论】:
-
struct hashTable *newTable;:newTable是NULL。不能像newTable[i].head = NULL;一样使用 -
关于您的次要但不相关的问题,请参阅What are the arguments to main() for?
-
首先,您没有为
newTable分配任何空间。你需要malloc一些空间newTable.. 虽然我猜你真正想要的是1struct hashTable和1000struct nodes?在这种情况下,我不会将newTable设为指针,只需使用struct hashTable newTable;,然后将malloc设为您想要的struct nodes 的数量。 -
@yano 这是正确的,我只需要一个带有 1000 个桶的 HashTable 并使用链接进行冲突。但是,如果我按照您的建议进行操作并分配我需要的结构节点的数量,例如,如果我没有将 Hashtable 设置为数组,我将如何输入一个值来表示 hashIndex 50?
-
您可以像索引数组一样索引指针。您已经这样做了,但没有分配内存。
标签: c pointers segmentation-fault malloc hashtable