首页 > 解决方案 > 指针之间的差异

问题描述

我知道代码是如何工作的。但不知道为什么?

指针之间有什么区别?

struct List{
   int val;
   List *next;
}
/// where is the different between fun1 and fun2 receiving the List
void fun1(List **head){}
void fun2(List *head){}
int main(){
    List *head;
     /// where is the different between fun1 and fun2 passing the List
    fun1(&head);
    fun2(head);
}

标签: c++

解决方案


两者之间的区别在于您引用的内存地址。

  • fun1(&head);: 你访问的内存地址就是head指针本身的内存地址。
  • fun2(head);:您访问的内存地址是head指向的位置。

尝试以head这种方式输出值:

void fun1(List **head){
    cout << "Pointer address: " << head << endl;
    cout << "Head points to: " << *head << endl;
}
void fun2(List *head){
    cout << "Head points to: " << head << endl;
}

输出将类似于:

Pointer address: 0x7ffeec04e058
Head points to: 0x104f2a036
Head points to: 0x104f2a036

通过使用&运算符,您正在访问变量的内存地址head


推荐阅读