xVictor
xVictor

Reputation: 77

What is the difference between passing &var to *var and var to var?

Basically, I want to know why this (passing the memory adress of list as parameter):

void init_lista (elemPtr *list) {
    *list = NULL;
}
int main(){
    elemPtr list;
    init_list(&list);
    //[...]
}

is different than this (passing just the content of list):

void init_lista (elemPtr list) {
    list = NULL;
}
int main(){
    elemPtr list;
    init_list(list);
    //[...]
}

OBS: elemPtr is a pointer type of a structure (typedef struct elem *elemPtr).

What I understand from &and *is that the first will get the var's memory adress and the latter will get the value referenced by it. Through this concept, both code sections should be equivalent, yet the first runs fine while the second compiles but gives me a runtime error. Why is that?

Upvotes: 1

Views: 1970

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311058

In this function

void init_lista (elemPtr list) {
    list = NULL;
}

list is a local variable of the function. You can imagine it like

void init_lista () {
    elemPtr list = NULL;
}

that is after exiting the function the variable will be destroyed. The original argument will not be changed because it is passed to the function by value. So the function deals with a copy of the original object.

In this function

void init_lista (elemPtr *list) {
    *list = NULL;
}

there is passed pointer to the original object. So changing of the argument through this pointer will be done for the original object.

Upvotes: 2

Related Questions