1

i have a beginner question about function in C, say I have a array of pointers to linked list and I want to write a function to add a pointer of a node to the array:

void addhash(int value,struct node ** arr[]){
    struct node *p =(struct node*)malloc(sizeof(struct node));
    p->value=10;
    arr[value]=&p;
};

Is this the correct way to define the function? when I run this in main, the bucket that I tried to add a node to is somehow still NULL.

2 Answers 2

1

arr[value]=&p is effectively returning a pointer to a local variable, which is never a valid thing to do. Local variables do not exist after the function returns. It looks like what you want is to declare the parameter as node *arr[] and change that line to arr[value]=p. That will correctly save a pointer to the memory you allocated for the node.

You may also want to think about whether it makes more sense to have the function just allocate and initialize the node structure and return that, at which point the caller can add it to the array.

Sign up to request clarification or add additional context in comments.

2 Comments

I defined my array with struct node **hashtable[10000];
so I think I should instead define it like struct node *hashtable[10000]; and rewrite my function accordingly then, thanks again!
0

In your exemple you are not adding the pointer of node but you are adding a pointeur of a pointeur to the node. the pointeur to the node is p if you save the adresse of p then you are saving the adresse of the pointer. we have p is a local variable so it will dislocate when we return from the function.

Rule: never try to save adresse of a local variable and use it outside the function that declare this variable.

void addhash(int value,struct node * arr[]){
struct node *p =(struct node*)malloc(sizeof(struct node));
p->value=10;
arr[value]=p;
};

I hope that I have answered your question

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.