由于“unsigned int”导致运行时错误

问题描述 投票:0回答:1

尝试解决217。包含 C 中的 Duplicate 和 HashSet。

在我尝试使计算的索引始终为(+)后,我收到错误。


#define BUCKET_SIZE 1000

typedef struct ListNodes {
  int val;
  struct ListNodes* next;
} ListNode;

typedef struct {
  ListNode* buckets[BUCKET_SIZE];
} MyHashSet;

// create hash table
MyHashSet* myHashSetCreate() {
    MyHashSet* obj = (MyHashSet*) malloc(sizeof(MyHashSet));
    for(int i = 0 ; i < BUCKET_SIZE ; i++ ) {
        obj -> buckets[i] = NULL;
    }
    return obj;
}

bool myHashSet(MyHashSet* obj, int key) {
    unsigned int index =  key % BUCKET_SIZE; // problem here
    ListNode* current = obj->buckets[index];
    while(current != NULL) {
        if(current -> val == key) return true;
        current = current -> next;
    } 
    
    ListNode* newNode = (ListNode*)malloc(sizeof(ListNode));
    newNode->val = key;
    newNode->next = obj->buckets[index];
    obj->buckets[index] = newNode;
    return false;
}

// task function

bool containsDuplicate(int* nums, int numsSize) {
     MyHashSet* obj = myHashSetCreate();
     for(int i = 0 ; i < numsSize ; i++) {
        if(myHashSet(obj, nums[i])) {
            return true;
        }
     }
    return false;
}


unsigned int index =  key % BUCKET_SIZE;

结果:

第 23 行:字符 15:运行时错误:加载地址 0x6258000078f0,空间不足以容纳“struct ListNode *”类型的对象 [solution.c] 0x6258000078f0:注意:指针指向这里

ListNode* current = obj->buckets[index];

我通过以下方式修复了错误:

int index =  key % BUCKET_SIZE;

int index =  key % BUCKET_SIZE;
    if( index < 0) {
        index *= -1;
    }

知道为什么代码表现得很奇怪吗?

c hashmap hashtable hashset unsigned
1个回答
0
投票

避免签名数学:

bool myHashSet(MyHashSet* obj, int key) {
    unsigned int index =  key % BUCKET_SIZE;

更改为

bool myHashSet(MyHashSet* obj, unsigned key) {
    unsigned int index =  key % BUCKET_SIZE;

© www.soinside.com 2019 - 2024. All rights reserved.