var和var传递给var有什么区别

var和var传递给var有什么区别

本文介绍了将& var传递给* var和var传递给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是结构(typedef struct elem *elemPtr)的指针类型.

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

我从&*所了解的是,第一个将获取var的内存地址,而第二个将获取其引用的值.通过这个概念,两个代码段应该等效,但是第一个代码段运行良好,而第二个代码段编译却给了我运行时错误.为什么呢?

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?

推荐答案

在此函数中

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

list是函数的局部变量.你可以想象像

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.

此功能

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.

这篇关于将& var传递给* var和var传递给var有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 04:16