为什么同一个指针的地址不同呢?

JPP*_*PPP 0 c++ pointers c++11

我正在尝试 C++ 上的链接列表,当我尝试打印列表的数据时,它给出了有趣的结果,告诉我列表为空。当我在 main 中打印变量的地址和在函数中打印同一变量的参数地址时,会给出不同的结果。有谁可以帮我解释一下吗,谢谢!这是代码:

#include <iostream>
using namespace std;

typedef struct link_node{
    int data;
    link_node* next;
};

void iter(link_node* head){
    link_node* cur = head;
    cout<<"The address of head in function: "<<&head<<endl;
    while(cur!=NULL){
        cur = cur->next;
        cout<<cur->data<<' ';        
    }
}

link_node *create(int a){
    link_node* head;
    link_node* cur;
    head =(link_node*) malloc(sizeof(link_node));
    cur = head;
    for(int i=a;i<a+10;i+=2){
        link_node * node = (link_node*) malloc(sizeof(link_node));
        node->data = i;
        cur->next = node;
        cur = node;
    }
    cur->next = NULL;
    return head;
}

int main(){
    link_node* head_1 = create(0);
    link_node* head_2 = create(1);
    link_node* result = (link_node*) malloc(sizeof(link_node));
    cout<<"The address of head_1: "<<&head_1<<endl;
    iter(head_1);

    return 0;    
}
Run Code Online (Sandbox Code Playgroud)

这是程序的输出:

The address of head_1: 0x61ff04
The address of head in function: 0x61fef0
0 2 4 6 8
Run Code Online (Sandbox Code Playgroud)

谢谢!

joh*_*ohn 5

headhead_1是两个不同的变量,因此它们有两个不同的地址。但这些变量的也是地址(或指针),并且这些值是相同的。

当您处理指针时,很容易混淆变量的地址和变量的值,因为它们都是指针(但指针类型不同)。

换句话说,所有变量都有地址,但只有指针变量才有值,而值也是地址。

试试这个代码

cout<<"The value of the head pointer: "<<head<<endl;

cout<<"The value of the head_1 pointer: "<<head_1<<endl;
Run Code Online (Sandbox Code Playgroud)