0

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

1 Answer 1

0

In C, all function parameters are passed by value, that is the values are copied into the parameters. (There a way to pass by reference instead, but I think that one makes code hard to read.)

So when you call hashInsert, it receives a struct list* of name theList, but the value is a copy of what was passed, if the function changes the value, nothing will change for the calling code.

One way to evade that is to use a pointer to pointer, like

void hashInsert(struct list **theList, string newValue)
{
    *theList = insert(*theList, newValue);
}
... 
    hashInsert(&names[num], "heey");

Another is to use not hashInsert, but insert, like

    names[num] = insert(names[num], "heey");

In the pointer to pointer version, it's still a copy, but this time pointing to the pointer you'd like to change.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .