gpt4 book ai didi

c - 赋值错误C

转载 作者:行者123 更新时间:2023-11-30 15:18:36 30 4
gpt4 key购买 nike

我是 C 语言新手,在指针和值方面遇到一些问题。

所以我正在制作一个哈希表,但我的插入函数出现错误(错误发布在代码之后):

typedef struct WordList {
char *word;
struct WordList *next;
} WordList;

typedef struct HashTable {
int key;
struct WordList *value;
struct HashTable *next;
} HashTable;

#define TABLE_SIZE 8192

HashTable *table[TABLE_SIZE] = { NULL };

//Insert element
void insertElement(int key, char *word) {
int i = 0;

// check if key has already existed
while((&(table[i]->key) != NULL) && (i < TABLE_SIZE)) {
// !!!! ERROR HERE !!!! if(table[i]->key == key) { // if find key
// ... implementation

return; // exit function and skip the rest
}

i++; // increment loop index
}

// find a NULL slot and store key and value
if(&(table[i]->key) == NULL) {
// !!! ERROR HERE!!! table[i]->key = key;

// ... implementation
}
}

int main() {
// test call
insertElement(1, "blah\0");

int i;

for ( i=0; i < 10; i++)
{
printf("%d: ", i);

struct HashTable *tableTemp = table[i];

while (tableTemp != NULL)
{
printf("(%d)\n", tableTemp->key);
tableTemp = tableTemp->next;
}

printf("\n");
}

return 0;
}

我使用 valgrind,这是我在分配表 [i]-> key = key 时遇到的错误

Invalid write of size 4
Address 0x0 is not stack'd, malloc'd or (recently) free'd

最佳答案

一般来说,地址0x0是空指针;您正在尝试使用空指针写入 4 字节值(可能是 int),例如 int *p = 0; *p = 1; 但它可能不是那么明目张胆。

在您的骨架代码中,您有:

if (&(table[i]->key) == NULL) {
// !!! ERROR HERE!!! table[i]->key = key;

评论:

  1. 您应该显示错误的实际代码。我们必须猜测,因为你还没有展示出来。

  2. 您刚刚验证了 table[i]->key 的地址是一个空指针,这在您尝试分配 table 时会导致问题[i]->key = key; 到它。

将来,请提供足够的真实代码,以便我们可以看到您的 MCVE ( How to create a Minimal, Complete, and Verifiable Example? ) 或 SSCCE ( Short, Self-Contained, Correct Example ) — 两个名称和链接表示相同的基本想法。

关于c - 赋值错误C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31322585/

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