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

烂漫一生 提交于 2019-12-11 12:44:28

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/28798322/what-is-the-difference-between-passing-var-to-var-and-var-to-var

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!