gpt4 book ai didi

c - 出现段错误 11 不确定在 C 中是否正确使用指针

转载 作者:行者123 更新时间:2023-11-30 16:55:50 27 4
gpt4 key购买 nike

请记住,我是 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书中的哈希表示例进行操作,然后随意修改以满足您的需求。

关于c - 出现段错误 11 不确定在 C 中是否正确使用指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40182794/

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