指针之间的差异

时间:2020-10-14 02:24:43

标签: c++

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

指针之间有什么区别?

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);
}

2 个答案:

答案 0 :(得分:3)

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

  • 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的内存地址。

答案 1 :(得分:0)

&获取某物的地址。在这种情况下,某种指向List的指针。指针只是保存某物的地址。因此,指向事物的指针的地址就是指向事物的指针的指针。