首页 > 解决方案 > 关于指针的问题

问题描述

我想将 hashnode 与节点链接起来。由于hashnodeNode**(指向节点指针的指针),因此 的值hashnode应该是节点指针的地址(即&node)。我的代码如下。

但是,它向我显示了一个错误,即分配给struct Node *from Node **(aka struct Node **) 的不兼容指针类型;消除 &。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct Hashnode
{
    int size;
    struct Node** hashnode;
}Hashtable;


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

int main(void)
{
    Node* node = malloc(sizeof(Node));
    node->word = "Elvin";
    node->next = NULL;
    printf("First Node created successfully!...\n");

    Hashtable hasht;

    hasht.size = 10;
    hasht.hashnode = malloc(sizeof(*hasht.hashnode)*hasht.size);
    for (int i = 0; i < hasht.size; i++)
    {
        hasht.hashnode[i] = NULL;
        printf("the address of the %i hashnode is: %p\n", i, hasht.hashnode[i]);
    }
    printf("The hashtable is created successfully!...\n");

    int key = 3;
    hasht.hashnode[key] = &node;
}

知道我做错了什么吗?我在概念上错了什么?

标签: cpointers

解决方案


知道我做错了什么吗?我在概念上错了什么?

虽然hashnode是指向 a 的指针struct Nodehashnode[key]但只是指向 a 的指针struct Node。但是&node又是指向 a 的指针的地址(或指针)struct Node。因此,以下分配失败:

hasht.hashnode[key] = &node;

编译器正确地抱怨。

您必须执行以下操作:

hasht.hashnode[key] = node;

推荐阅读