简体   繁体   中英

Why does my C code for inserting an element into a hash tree work in Main() but not when I call it via function?

I'm fairly certain this has something to do with pointers and the function using copies instead, but I'm not sure how...because I've inserted the pointer as a parameter for create();

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

typedef struct list {
    string word;
    struct list *next;
}
linkedList; 

struct list* create (string newWord) {
    linkedList *new = malloc(sizeof(newWord));
    new->word = newWord;
    new->next = NULL;
    return new;
}

struct list* insert (struct list *theList, string newValue) {
    linkedList *anotherOne = create(newValue);
    anotherOne->next = theList;
    return anotherOne;
}

int hash (string name) {
    return strlen(name);
}

void hashInsert (struct list *theList, string newValue) {
    theList = create(newValue);
    }

int main(void) {
   linkedList *names[24] = {NULL};
   int num = hash("heey");
 //  names[num] = create("heey"); // <- this code works when I uncomment it
   hashInsert(names[num], "heey"); // <-- this causes a segfault.. idk why
   printf("%s", names[num]->word);
}

Your hashInsert function creates a local copy of the pointer ( theList ), you modify said local copy, but the actual pointer in your main function is still set to NULL . Calling printf on that is the cause of your segmentation fault.

You can resolve this issue by passing a pointer to the pointer to your function

void hashInsert(string list **theList, string newValue) {
    *theList = create(newValue);
}

and then call it

hashInsert(&names[num], "heey");

This way, you modify the value of the pointer from main .

EDIT

Also, as the comments state, your malloc does indeed not allocate enough memory, you also need some memory to store the next list pointer.

The problem is with you hashInsert function. It takes the pointer by value (so the original pointer you pass isn't modified). There's a much better way to go about this-

struct list* hashInsert(char* string){
    return create(string);
}

A few points aside from that, don't use string , always use char* since that what it really is. I see you're using some library, but you're better off simply including the proper headers yourself, in this case, you should include stdlib.h since it contains the definition of malloc() .

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