C语言 在将NULL插入到结构数组中时,“赋值给类型时类型不兼容”

xe55xuns  于 2023-08-03  发布在  其他
关注(0)|答案(3)|浏览(118)

我正在尝试在C中实现链接(哈希)。到目前为止,我已经编写了以下代码:

#include<stdio.h>
#include<stdlib.h>
#define size 10

typedef struct hashNode
{
    int data;
    struct hashNode *next;
} node;

int main()
{
    node chain[size];
    
    for(int i=0; i<=(size-1); i++)
        chain[i] = NULL;
    
    //insert(chain, 10);
    
    return 0;
}

字符串
我得到以下错误:

In file included from /usr/include/stdlib.h:31,
                 from chaining.c:2:
chaining.c: In function ‘main’:
chaining.c:33:14: error: incompatible types when assigning to type ‘node’ {aka ‘struct hashNode’} from type ‘void *’
   33 |   chain[i] = NULL;
      |              ^~~~

uoifb46i

uoifb46i1#

看起来你试图让所有的node一开始都指向NULL,但是node不是指针。它们有一个名为next的指针成员,所以你应该做的是:

for(int i=0; i<=(size-1); i++)
    chain[i].next = NULL;

字符串
你也可以跳过循环,直接在定义数组时初始化它:

node chain[size] = {0};


旁注:不要写i<=(size-1)。它有一个额外的认知负荷,在sizeunsigned类型(这是常见的)的情况下是不安全的。写i < size

i1icjdpr

i1icjdpr2#

NULL通常用于指示指针没有指向任何有效的内存位置。Chain是一个节点对象的数组,而 * 不是 * 一个指向节点对象的 * 指针 * 的数组,因此你必须设置一个指针。

node *chain[size];

字符串
我还看到你正在循环size - 1,这是多余的,会导致unsigned数据类型中的意外行为。你可以简单地使用i < size

for(int i = 0; i < size; i++)
    chain[i] = NULL;


编辑:感谢@fe2o3指出使用循环将所有元素设置为NULL是老派的,我完全同意。
还有其他方法可以使用,例如使用memsetcallocdesignated initialization与较新的编译器。
使用memset

memset(chain, 0, sizeof(chain));


使用designated inits:文档here

node* chain[SIZE] = { [0 ... SIZE - 1] = NULL };


最后,使用calloc:尽管如此,确保在完成后释放分配的MEMS。

node** chain = (node**)calloc(SIZE, sizeof(node*));
//Free when you're done...
free(chain);

ojsjcaue

ojsjcaue3#

node chain[size];
    
    for(int i=0; i<=(size-1); i++)
        chain[i] = NULL;

字符串

  1. i<=(size-1) => i < size
  2. chain[i]是一个结构体,不是指针,你不能给它赋NULL。
  • 你可以使用复合文字来代替:
chain[i] = (node){0};

  • 可以使用memset
memset(&chain[i], 0, sizeof(chain[i]));

  • 或者如果它只是一个初始化:
node chain[size] = {0,};

相关问题