GPT 代码改
#include <stdio.h>
#include <stdlib.h>
#include <string.h>#define TABLE_SIZE 256struct Node {char *key;void *value;struct Node *next;
};struct HashTable {struct Node *table[TABLE_SIZE];
};void initHashTable(struct HashTable *hashTable) {for (int i = 0; i < TABLE_SIZE; i++) {hashTable->table[i] = NULL;}
}int hashFunction(char *key) {unsigned long hash = 0;int c;while ((c = *key++)) {hash = c + (hash << 6) + (hash << 16) - hash;}return hash % TABLE_SIZE;
}void insert(struct HashTable *hashTable, char *key, void *value) {int index = hashFunction(key);struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));if (newNode == NULL) {fprintf(stderr, "Memory allocation failed\n");exit(EXIT_FAILURE);}newNode->key = strdup(key);newNode->value = value;newNode->next = NULL;newNode->next = hashTable->table[index];hashTable->table[index] = newNode;
}void *get(struct HashTable *hashTable, char *key) {int index = hashFunction(key);struct Node *current = hashTable->table[index];while (current != NULL) {if (strcmp(current->key, key) == 0) {return current->value;}current = current->next;}return 0;
}void removeKey(struct HashTable *hashTable, char *key) {int index = hashFunction(key);struct Node *current = hashTable->table[index];struct Node *prev = NULL;while (current != NULL) {if (strcmp(current->key, key) == 0) {if (prev == NULL) {hashTable->table[index] = current->next;} else {prev->next = current->next;}free(current->key);free(current);return;}prev = current;current = current->next;}
}void freeHashTable(struct HashTable *hashTable) {for (int i = 0; i < TABLE_SIZE; i++) {struct Node *current = hashTable->table[i];while (current != NULL) {struct Node *next = current->next;free(current->key);free(current);current = next;}}
}void hello() { printf("hello\n"); }
void world() { printf("world\n"); }int main() {struct HashTable hashTable;initHashTable(&hashTable);insert(&hashTable, "hello", hello);insert(&hashTable, "world", world);((void (*)())get(&hashTable, "hello"))();freeHashTable(&hashTable);return 0;}
对驱动来说,别名映射很重要,就像生活不能没有太阳
修改后