简体   繁体   中英

Questions about pointer to pointer

i would like to link the hashnode with the node. As hashnode is the Node** (a pointer to pointer of node), hence the value of hashnode should be the address of node pointer (ie &node ). my code is below.

However, it shows an error to me that incompatible pointer types assigning to struct Node * from Node ** (aka struct Node ** ); remove &.

#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;
}

any idea what i did wrong? What am i conceptually wrong?

You have hashnode set up as an array of pointers. So you want to assign a pointer to a given array element, not the address of a pointer:

hasht.hashnode[key] = node;

any idea what i did wrong? What am i conceptually wrong?

Although hashnode is a pointer to pointer to a struct Node , hashnode[key] is only a pointer to a struct Node . But &node is again an address (or pointer) to a pointer to a struct Node . So the following assignment fails:

hasht.hashnode[key] = &node;

And the compiler complains rightly.

You have to do the following:

hasht.hashnode[key] = node;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM