我正在尝试实现链接(哈希)。我不想全局声明
node *chain[size]
并希望它在 main 中声明它并通过函数将其作为参数传递。为此,我将代码修改为以下代码:
#include<stdio.h>
#include<stdlib.h>
#define size 10
typedef struct hashNode
{
int data;
struct hashNode *next;
} node;
void insert(node *chain, int data)
{
node *baby = (node*)malloc(sizeof(node));
baby->data = data;
baby->next = NULL;
int key = data % size;
if(chain[key]==NULL)
chain[key] = baby;
else
{
baby->next = chain[key];
chain[key] = baby;
}
}
int main()
{
node *chain[size];
for(int i=0; i<size; i++)
chain[i] = NULL;
insert(chain, 10);
return 0;
}
代码给出了多个错误:
chaining.c: In function ‘insert’:
chaining.c:21:15: error: invalid operands to binary == (have ‘node’ {aka ‘struct hashNode’} and ‘void *’)
21 | if(chain[key]==NULL)
| ~~~~~~~~~~^~
| |
| node {aka struct hashNode}
chaining.c:22:16: error: incompatible types when assigning to type ‘node’ {aka ‘struct hashNode’} from type ‘node *’ {aka ‘struct hashNode *’}
22 | chain[key] = baby;
| ^~~~
chaining.c:27:16: error: incompatible types when assigning to type ‘struct hashNode *’ from type ‘node’ {aka ‘struct hashNode’}
27 | baby->next = chain[key];
| ^~~~~
chaining.c:28:16: error: incompatible types when assigning to type ‘node’ {aka ‘struct hashNode’} from type ‘node *’ {aka ‘struct hashNode *’}
28 | chain[key] = baby;
但是,如果我在结构之后全局声明数组链,则相同的代码可以完美运行:
typedef struct hashNode
{
int data;
struct hashNode *next;
} node;
node *chain[size];